Menu

  • Home
  • Javascript (JS)
  • Node JS
  • React JS
  • React Native
  • More
    • Electron JS
    • WordPress
    • About
    • Code Examples
  • Contact Us
  • Our Services
  • +237 673917344
  • info@alljavascript.net
  • New Content Weekly
Beyond JavaScript Beyond JavaScript
  • Home
  • Javascript (JS)
  • Node JS
  • React JS
  • React Native
  • More
    • Electron JS
    • WordPress
    • About
    • Code Examples
  • Contact Us
  • Our Services
  • July 21, 2022
  • admin
  • 0 Comments
  • 193 Views
  • 1 Likes
  • MongoDB, Node JS

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.

preview of data to be sent and cmd line window showing server connected and running status

Output

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

The hooks worked successfully..Notice the texts for before and after are logged in order, telling us the functions were executed before and after the data was saved in the database.
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,

read also: How to log Node JS http requests using morgan

Spread the love
Prev PostHow to send Json response in express js
Next PostIntroduction To Express Middleware
Related Posts
  • How to Make API Calls in Electron.js: A Step-by-Step Tutorial February 7, 2024
  • How to Open and Read an Excel File in Node.js: A Step-by-Step Tutorial February 7, 2024

Leave a Comment Cancel Comment

Your email address will not be published. Required fields are marked *

Recent Posts

  • How to Make API Calls in Electron.js: A Step-by-Step Tutorial
  • How to Open and Read an Excel File in Node.js: A Step-by-Step Tutorial
  • Electron.js and Express.js backend: A Comprehensive Tutorial
  • How to Get Started with Electron.js: A Tutorial for Beginners
  • How to add Favicon in Express.js: A Step-by-Step Tutorial

Recent Comments

No comments to show.

Popular Posts

February 7, 2024 / Electron JS, Node JS
How to Make API Calls in Electron.js: A Step-by-Step Tutorial
February 7, 2024 / Javascript (JS), Node JS
How to Open and Read an Excel File in Node.js: A Step-by-Step Tutorial
February 7, 2024 / Electron JS, Javascript (JS)
Electron.js and Express.js backend: A Comprehensive Tutorial

Tags

Express Js Json Morgan Node JS NPM

Categories

  • Electron JS
  • Html, CSS
  • Javascript (JS)
  • MongoDB
  • Node JS
  • React Native

We are a community of developers aimed at teaching code and solving coding problems. We provide coding articles, opportunities, content, videos and tutorials to help developers around the world...

Our Services

  • Website Design
  • Domain and Web Hosting
  • Tutoring
  • Mobile Apps
  • Website Content Writing

Recent Posts

  • How to Make API Calls in Electron.j

    Feb 7, 2024

  • How to Open and Read an Excel File

    Feb 7, 2024

Useful Links

  • Home
  • Services
  • Blog #2
  • About Us
  • Contact Us
  • Request Tutorials
  • Jobs
  • Volunteer
  • Hire Us
  • Support
info@alljavascript.net Drop Us a Line
+237 673917344 Call Us Now
Africa Get Direction
Copyright 2022 alljavascript.net, All rights reserved.