lean() on

After a few months in production, one of our microservices had some performance issues. I was given the task of optimizing its’ DB queries.


Though my experience with mongoose and MongoDB isn’t vast, I was able to find few quick wins. The first one was using mongoose’s lean() option.

By default, mongoose converts plain javascript objects returned from MongoDB to MongooseDocuments. These mongoose objects contain some mongoose magic, including the save method, getters/setters and more.

But with this extra functionality comes an overhead which affects the query’s performance…

Adding the lean() option prevents the mongoose document creation and returns a plain javascript object, thus resulting in better performance.

Usage Example

InfinityStones.find({name: 'Soul Stone'}).exec()

Now with lean:

InfinityStones.find({name: 'Soul Stone'}).lean().exec()

And that’s it


In addition to find(), the following queries also supports lean: findOne(), findById(), findOneAndUpdate(), and findByIdAndUpdate().

To conclude, the rule of thumb I found for using lean is this:

If your query is mostly focused on reading the data, with no need of mongoose functionality for advanced manipulations - add lean

Lean On youtube link

comments powered by Disqus