How does Query.prototype.batchSize() work in Mongoose ?
Last Updated :
12 Mar, 2021
The Query.prototype.batchSize() is used to set the batchSize option. The batchSize() function basically instructs the driver to retrieve a certain number of items per time.
Syntax:
Query.prototype.batchSize()
Parameters: This function has one array parameter i.e. number defining the batch size.
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
After that, you can just create a folder and add a file for example, index.js as shown below.
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 }
});
const query = User.find();
query.batchSize(100);
console.log( "The batch size set is :" , query.options)
|
The project structure will look like this:
Run index.js file using below command:
node index.js
Output:
The batch size set is : { batchSize: 100 }
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 }
});
const query = User.find();
query.batchSize(140);
console.log( "Batch Size defined is:" , query.options)
app.listen(3000, function (error ){
if (error) console.log(error)
console.log( "Server listening on PORT 3000" )
})
|
The project structure will look like this:
Run index.js file using below command:
node index.js
Output:
Server listening on PORT 3000
Batch Size defined is: 140
Reference:https://mongoosejs.com/docs/api/query.html#query_Query-batchSize
Share your thoughts in the comments
Please Login to comment...