Mongoose lean()

Improve Performance of Mongoose Query Using lean() method If you are new to MongoDB take a look at Learn MongoDB And Its Important Queries Within Five Days -1

watch If you are using node.js and MongoDB then you will be familiar with mongoose. Mongoose provides a straight-forward, schema-based solution to model your application data. In this post, we are going to look into performance improvement of Mongoose Queries without modifying your query and by just adding lean() method to it.

go to link You may wonder, Usual performance improvement of Database Query involves the addition of the new indices and fine tuning of the Query and Answer is yes, At the database end we need to add right indexes and need to fine-tune the query to get faster responses. By adding lean() method, will further improve the total performance of the application.

click here Consider a basic mongo Query:

watch const mongoose = require('mongoose'); const Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/test'); SampleModel.find().exec(function(err, data){ console.log(data); }); Consider 250 data available in the collection. Total Execution time for the above code is 92.809ms.

Now, Let’s use lean() method and will check the total time taken for the execution of the query.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;


SampleModel.find().lean().exec(function(err, data){

Total Execution time for this code is 46.748ms.

With lean() total time is reduced to half of the total time with the normal query.

enter site Let’s see what changed from normal query to lean().

Usually, normal mongoose find will return data with some prototype methods like save(), remove(), validate() and etc. However with lean() only return normal JSON object. Total output size is reduced and hence data will be retrieved fast.