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
- How to interact with input in Reactjs - How to handle state and event of input element in React apps
- How to populate multiple MongoDB objects on the same path in express-node - How to populate multiple objects in MongoDB in the same path
- How to populate selected fields in a mongo document path in expressjs - How to populate object in mongo doc at a specific path with specific fields
- How to populate and display nested mongo objectin express-node route - How to populate object in express-MongoDB app
- How to render mongo object in Reactjs - How to render MongoDB object/ObjectId in React/MERN app
- How to render list of mongo objects in React component - How to render list of mongo objects in Reactjs
- How to place custom route links in Reactjs component - How to place custom links to routes/page in Reactjs
- How to filter MongoDB object list in express-node app - How to filter a mongo object list in document in express-node app
- How to fix mongo object Type error in Reactjs - How to fix TypeError/undefined in React - MERN application
- How to create document using mongoose in express-node app - How to save MongoDB document to the collection using mongoose REST operations