Open In App

Mongoose Query.prototype.exec() API

Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose Query API.prototype.exec() method of the Mongoose API is used on the Query objects. It allows us to execute the query operation to get the resulted data. Using this method we can also provide the query operation as a parameter to the method. Let us understand the exec() method using an example.

Syntax:

query.exec( operation, callback );

Parameters: This method accepts two parameter as described below:

  • operation: It is used to specify the operation you want to execute with exec method.
  • callback: It is used to specify the callback function which will be called to handle the promise.

Return Value: This method returns promise which can be handled using callback function or then and catch block.

Setting up Node.js Mongoose Module:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this: 

 

Database Structure: The database structure will look like this, the following database present in the MongoDB.

Example 1: The below example illustrates the basic functionality of the Mongoose Connection exec() method. We are just executing the find() method result using this method and handling the promise returned by exec() method by providing callback function.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
 
// Set Up the Database connection
 
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
 
const studentSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: Number,
    rollNumber: { type: Number, required: true }
});
 
const StudentModel = connectionObject.model('Student', studentSchema);
 
StudentModel.find().exec((error, result) => {
    if (error) {
        console.log(error);
    } else {
        console.log(result);
    }
})


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

[
{
_id: new ObjectId("63a40a1065e8951038a391b1"),
name: 'Student1',
age: 30,
rollNumber: 9,
__v: 0
},
{
_id: new ObjectId("63a4a98407370cdcd1961b1a"),
name: 'Student3',
age: 17,
rollNumber: 178,
__v: 0
},
{
_id: new ObjectId("63a4a9a207370cdcd1961b2c"),
name: 'Student2',
age: 18,
rollNumber: 176,
__v: 0
},
{
_id: new ObjectId("63c1330b76ed3b6397607f77"),
name: 'Student4',
age: 25,
rollNumber: 1025,
__v: 0
},
{
_id: new ObjectId("63c1335b1e51e14cbbb4c57b"),
name: 'Student5',
age: 15,
rollNumber: 7,
__v: 0
}
]

Example 2: The below example illustrates the basic functionality of the Mongoose Connection exec() method. In this example, we are updating one of the document in our collection by providing operation name and callback function to the exec() method.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
 
// Set Up the Database connection
 
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
 
const studentSchema = new mongoose.Schema({
    name: { type: String, required: true },
    age: Number,
    rollNumber: { type: Number, required: true }
});
 
const StudentModel = connectionObject.model('Student', studentSchema);
 
const query = StudentModel.update(
    { name: "Student1" }, { age: 20 }
);
query.exec('update', (error, result) => {
    if (error) {
        console.log(error);
    } else {
        console.log(result);
    }
})


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}

GUI Representation of the Database using Robo3T GUI tool:

Note: After the release of latest version 7, mongoose remove the support for callback in .exec() and now we can use .then, .catch of promises or try-catch of async-await.

Here is the updated example 1 with the help of .then and .catch

Javascript




StudentModel.find().exec()
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.log(error);
  });




Last Updated : 21 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads