How does Query.prototype.exec() work in Mongoose?
Last Updated :
17 Mar, 2021
The Query.prototype.exec() function is used to execute the query. It can handle promises and executes the query easily. The callback can be passed as an optional parameter to handle errors and results.
Syntax:
Query.prototype.exec()
Parameters: This function has two optional parameters, one is callback function and another is operation of string or function type.
Return Value: This function returns Query Object.
Installing mongoose :
npm install mongoose
After installing the mongoose module, you can check your mongoose version in command prompt using the command.
npm mongoose --version
Now, create a folder and add a file, for example, index.js as shown below.
Database: The sample database used here is shown below.
Project Structure: The project structure will look like this.
Example 1:
index.js
const mongoose = require( 'mongoose' );
useNewUrlParser: true ,
useCreateIndex: true ,
useUnifiedTopology: true
});
const User = mongoose.model( 'User' , {
name: { type: String },
age: { type: Number }
});
var query = User.find();
query.exec( function (err, res){
if (err) console.log(err)
console.log(res)
})
|
Run index.js file using below command:
node index.js
Output:
[
{ _id: 5ebb9129a99bde77b2efb809, name: 'Gourav', age: 10, __v: 0 },
{ _id: 5ebc3669a99bde77b2efb9ba, name: 'Lalit', age: 25, __v: 0 },
{ _id: 5ebc367da99bde77b2efb9bf, name: 'Piyush', age: 5, __v: 0 },
{ _id: 5ebd345f5d2d8a3534b2f391, name: 'Manish', age: 34, __v: 0 }
]
Example 2:
index.js
const express = require( 'express' );
const mongoose = require( 'mongoose' );
const app = express()
useNewUrlParser: true ,
useCreateIndex: true ,
useUnifiedTopology: true
});
const User = mongoose.model( 'User' , {
name: { type: String },
age: { type: Number }
});
var query = User.find({age:{$gte:20}});
query.exec( function (err, res){
if (err) console.log(err)
console.log(res)
})
app.listen(3000, function (error ) {
if (error) console.log(error)
console.log( "Server listening on PORT 3000" )
});
|
Run index.js file using below command:
node index.js
Output:
Server listening on PORT 3000
[
{ _id: 5ebc3669a99bde77b2efb9ba, name: 'Lalit', age: 25, __v: 0 },
{ _id: 5ebd345f5d2d8a3534b2f391, name: 'Manish', age: 34, __v: 0 }
]
Reference:
https://mongoosejs.com/docs/api/query.html#query_Query-exec
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...