1212
GitHub - eikw/mongoose-slugger · GitHub
Skip to content

eikw/mongoose-slugger

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Slugger for Mongoose

Automatically generates so called “slugs” for Mongoose documents. Slugs are typically used as human-readable parts of URLs instead of machine-readable identifiers (see e.g. here or here).

In case a slug is already taken by an existing document, the plugin automatically creates a new one (typically using a sequence number) and keeps trying until the document can be saved successfully.

There exist several similar Mongoose plugins already, however, none of them fit our requirements. These are:

  • We do not want to maintain a separate collection for storing any state.

  • Saving with a generated slug must work atomically. This means: First performing a query to check whether a slug is not yet taken and then saving a document is not acceptable!

  • We need the ability for “scoped” tags. This means: Slugs can be unique with regards to other document properties (e.g. have unique person name slugs in regards to a place, …)

  • Must work with callbacks and promises.

  • It must be possible to specify the slug generation strategy.

Usage

const schema = new mongoose.Schema({
  firstname: String,
  lastname: String,
  city: String,
  slug: String
});

// create a unique index for slug generation;
// here, the slugs must be unique for each city
schema.index({ city: 1, slug: 1 }, { name: 'city_slug', unique: true });

// set the plugin options
schema.plugin(slugger.plugin, {
  // the property path which stores the slug value
  slugPath: 'slug',
  // specify the properties which will be used for generating the slug
  generateFrom: [ 'firstname', 'lastname' ],
  // the unique index, see above
  index: 'city_slug'
});

const Model = mongoose.model('MyModel', schema);

// make sure to wrap to Mongoose model
Model = slugger.wrap(Model);

Development

Install NPM dependencies with yarn.

To execute the tests, use the test.sh script. It starts a new MongoDB Docker container and then executes the test cases.

Why yet Another Tool?

There’s a plethora of similar plugins, most of them old and abandoned though. Here’s a list, sorted by recent activity (first was updated recently when writing this):

Contributing

Pull requests are very welcome. Feel free to discuss bugs or new features by opening a new issue.


Copyright Philipp Katz, LineUpr GmbH, 2018

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • TypeScript 98.0%
  • Shell 2.0%