DEV Community

Cover image for Why Mongoose ?
Md. Rezaul Islam Rana
Md. Rezaul Islam Rana

Posted on

Why Mongoose ?

Mongoose is a popular ODM(Object Data Modeling) library for MongoDB with Node JS. ODM is a programming concept that means defining a schema for data in a way that aligns with the structure of the objects in application. Mongoose provides a higher level schema clearance over MongoDB and makes it easier for developers to work with mongoDB using JavaScript or Typescript.
Here are some reasons why we use mongoose:
Schema definition: Everything in Mongoose starts with a schema. Schema means a blueprint that defines the structure of documents within a collection, including the fields, types, validation rules, and default values. This helps maintain consistency in data structure, making it easier to validate.

import mongoose from 'mongoose';
const { Schema } = mongoose;

const blogSchema = new Schema({
title: String, // String is shorthand for {type: String}
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
});
To use schema we have to convert it into a model.
mongoose.model(modelName, schema)

Middleware support: Middleware refers to functions that are executed at the specific points in the lifecycle of documents.Mongoose provides some built-in hooks such as “pre” “post” which allow it to perform certain operations like saving ,updating and removing documents.
Usage of “Pre” hooks—
const schema = new Schema({ /* ... */ });
schema.pre('save', function(next) {
// do stuff
next();
});

Usage of “post” hooks—
schema.post('init', function(doc) {
console.log('%s has been initialized from the db', doc._id);
});
schema.post('validate', function(doc) {
console.log('%s has been validated (but not saved yet)', doc._id);
});
schema.post('save', function(doc) {
console.log('%s has been saved', doc._id);
});
schema.post('deleteOne', function(doc) {
console.log('%s has been deleted', doc._id);
});

Top comments (0)