Mongo with mongoose

How to automatically create slugs for mongoose schema in Express-Nodejs app


Slugs can be replacement of post id of your blog . Using title or a string we can generate clean url slugs. It can be used with Mongoose(Mongoose is a npm package driver for NoSQL MongoDB ) Model or any Model class. The slugify npm package is ready to serve our requirement. Install the package using

npm i slugify --save

Here is our Mongoose Post Model Schema definition

const mongoose = require("mongoose");
const slugify=require('slugify')
const postSchema = new mongoose.Schema({
 
 title: { type: String, required: true },
 excerpt: { type: String },
 slug: { type: String,required:true,unique:true },
  );
postSchema.pre('validate',function(next){
if(this.title){
 this.slug=slugify(this.title,{lower:true,strict:true})
}
next()
})
module.exports = mongoose.model("Post", postSchema);
‚Äč

Validate and Generate slugs automatically

The postSchema.pre(‘validate’,function(next) can be used to validate the model fields and then we can auto generate neat slug based on the title and then store the slug into the model.

Slugify also remove special character ,semicolon ect from the string passed to it. These option are passed as parameters ({ })

The pre validation is invoked when a new object is created and save it to the database / document collection.

The slugify is handy tool when we are dealing with blog app or discussion forums.

You may also interested in the following mongoose posts

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.