Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Mongoose Schema.prototype.pre() API

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The Mongoose Schema API pre() method is used to add a pre-hook to the mongoose Schema methods and can be used to perform pre Schema method operations. 

Syntax:

Schema.prototype.pre(methodName, options, callback)

Parameters: It accepts the following parameters as mentioned above and described below:

  • methodName: It denotes the name of the Schema method name, or regex for the method name, to apply the pre middleware to 
  • options: It is an optional mongoose object that contains options.document and options.query.
  • callback: It is a callback function that accepts the parameter next.

Return type: It returns a Schema object as a response.

Creating node application And Installing Mongoose:

Step 1: Create a node application using the following command:

mkdir folder_name
cd folder_name
npm init -y
touch main.js

Step 2: After completing the Node.js application, Install the required module using the following command:

npm install mongoose

Example 1: In this example, we will use this method to log the filters applied to the mongoose query.

Filename: main.js

Javascript




// Importing the module
const mongoose = require('mongoose')
  
// Creating the connection
    {
        dbName: 'event_db',
        useNewUrlParser: true,
        useUnifiedTopology: true
    }, err => err ? console.log(err)
        : console.log('Connected to database'));
  
const personSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    age: {
        type: Number,
    }
});
  
personSchema.pre(/^find/, function (next) {
    console.log(this.getFilter());
});
  
const personsArray = [
    {
        name: 'Luffy',
        age: 20
    },
    {
        name: 'Nami',
        age: 20,
    },
    {
        name: 'Zoro',
        age: 35
    }
]
  
const Person = mongoose.model('Person', personSchema);
  
(async () => {
    await Person.insertMany(personsArray)
    await Person.find({ name: "Luffy", age: 20 })
})()

Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

GUI Representation of the  Database using MongoDB Compass:

 

Example 2: In this example, we will use this method to update the name of a mongoose document before saving it to the MongoDB

Filename: main.js

Javascript




// Importing the module
const mongoose = require('mongoose')
  
// Creating the connection
    {
        dbName: 'event_db',
        useNewUrlParser: true,
        useUnifiedTopology: true
    }, err => err ? console.log(err)
        : console.log('Connected to database'));
  
const personSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    age: {
        type: Number,
    }
});
  
personSchema.pre('save', function (next) {
    if (this.name === 'Luffy') {
        this.name = 'Nami'
    }
  
    next()
});
  
const Person = mongoose.model('Person', personSchema);
  
(async () => {
    const person = new Person({ name: 'Luffy', age: '19' })
    await person.save()
})()

Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

GUI Representation of the  Database using MongoDB Compass:

 

Reference: https://mongoosejs.com/docs/api/schema.html#schema_Schema-pre


My Personal Notes arrow_drop_up
Last Updated : 24 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials