Automatically generate a unique and url-friendly alias/slug and store it in Mongoose
Automatically generate a unique and url-friendly alias/slug and store it in Mongoose. Assumes you have a field on which the alias is based on. For posts it's common to generate an alias from the title.
Define your model like this:
var mongoose = require'mongoose'monguurl = require'monguurl';Post =title: type: Stringslug: type: string index: unique: true;Postpluginmonguurlsource: 'title'target: 'slug';mongoosemodel'Post' Post;
And then if you for example create a new document like this:
mongoosemodel'Post'createtitle: 'This is so Äwesome!';
The slug will be automatically generated and stored in the database:
Create another identical document and it will be stored like this:
The ending number will increase to "-100", then it will be "-100-2". This is to avoid ruining intentional numbers such as "It's over 9000" or "A day in 2013". It's unlikely enough that either such a title is repeated or that the same title is used more than a hundred times anyway.
Also note that theoretically this plugin can be used without a source/title, if such behavior is desired. Just set the target field when creating the document and any source will be ignored.
npm install monguurl --save