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

Work with MangoDB using mongoose in Nodejs-Express app


MangoDB is a NoSQL database which can be backend for web/mobile application. Working with Nodejs Express app, what I feel is Python Flask like environment, rendering, templating etc everything in place.

Mongoose

Mongoose is MangoDB modeling tool, which is designed to work with asynchronous environment (none blocking code). The following is required to use mongoose in your app

  1. mongoose module
  2. Connection string
  3. Schema
  4. Model

Install Mongoose

Install mongoose  from npm library by executing command on the terminal

npm install mangoose -save  *

*The save option will add mongoose into dependecies section of package.json (do you know, can install all dependencies of  project by firing npm install command on shell)

Continue reading Work with MangoDB using mongoose in Nodejs-Express app