
What are Mongoose Hooks
Mongoose Hooks Concepts And Examples (pre and post hooks)
Hi devs..In this tutorial, we are going to cover Mongoose middleware.
Generally, middleware in node js are simply functions or block of code that are executed during a process(or cycle) and can make changes to that process or cycle.
For example, we have express middleware.
Mongoose middleware has a similar logic. Mongoose has practically 4 types of middleware;
document middleware, model middleware, aggregate middleware and query middleware
Prerequisite
- Basic express js, postman, mongoose and mongoDB knowledge.
- Have node js, postman, mongoose and express installed.
(we are going to use Mongodb Atlas)
Lets get started!
Every middleware mentioned above support the pre and post hook.
Let me explain!-
The pre and post hook are simply levels in which your code can be executed when carrying out an operation using mongoose and mongoDB.
As the name implies, “pre” comes in before the operation is carried out (with the database) while “post” is executed after the operation is complete.
The syntax is just very straight forward:
schema.pre(‘…’) || schema.post(‘…’)
The arguments passed within the bracket is the operation carried out with the database (save document, remove document …) and a callback function (block of code to be executed as per pre or post).
Note: Your pre or post hook should be placed at the Schema level (before your model).
read also: How to send Json response in express js
Example:
The code below is a simple express app with a pre and post hook that logs a message on the command line console before and after a document is saved in the database.
kindly replace the mongoDB connection URL with either your local database or your online mongoDB atlas credentials.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
//connect database
mongoose.connect(
'mongodb+srv://<username>:<yourpassword>@testcluster.3sasu.mongodb.net/Alida-coding-School?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
).then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
//set schema
const dataSchema = new mongoose.Schema({
name: String,
email: String,
})
//pre hook
dataSchema.pre('save', function (next) {
console.log('before doc is saved');
next()
})
//post hook
dataSchema.post('save', function () {
console.log('after doc is saved');
});
const dataModel = mongoose.model('user', dataSchema) //compile to model
app.use(bodyParser.json())
//get route
app.get('/', (req, res) => {
res.send('home')
})
//post route
app.post('/', (req, res) => {
dataModel.create(req.body)
.then((doc) => {
res.json({ new_user: doc })
})
});
app.listen(3000, () => {
console.log('code running on port 3000');
})
– lets start the express js server, open postman and post data corresponding to our schema.

Output

Data saved successful!
Now lets check our console if the pre and post hooks worked like magic!

Finally lets check our database…Just for “check sake” ??

hurray!!!!!!!!
Thanks for coding with me..
Hope you learnt something new. You can always drop your comments and share with other devs.
Thanks…see you again!
Links: Express JS Doc, Mongoose,
Leave a Comment