Contents
Mongoose is a schema-based solution to model your application data in MongoDB. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.
Mongoose offers various methods to retrieve documents from a collection, such as find()
, findOne()
, and findById()
. Although find()
is the most commonly used method and returns multiple documents based on a specified condition, it can lack performance when dealing with a large number of documents in a collection. To optimize the performance of find()
when handling a large number of documents, Mongoose provides the lean()
method. This method, when used with find()
, retrieves documents more quickly than find()
alone and is less memory intensive too. The result documents are plain old JavaScript objects (POJOs), not Mongoose documents. In this post, you’ll learn more about the tradeoffs of using lean()
.
Using Lean
Mongoose queries typically return an instance of the Mongoose Document class as the default behavior. However, these documents are significantly heavier than vanilla JavaScript objects due to the extensive internal state required for change tracking. By enabling the “lean” option, Mongoose skips instantiating a full Mongoose document and instead provides a POJO (plain old JavaScript object) that is much lighter. Let us understand this with example.
|
|
Let us now insert some records and then retrieve the documents
|
|
After executing a query, Mongoose internally converts the query results from POJOs to Mongoose documents. However, by enabling the “lean” option, Mongoose bypasses this step and directly returns the query results as POJOs.
|
|
The downside of enabling lean is that lean docs don’t have:
- Change tracking
- Casting and validation
- Getters and setters
- Virtuals
save()
|
|
Lean and Populate
You can use populate()
in combination with lean()
to make the populated documents and top-level documents lean. In the example below, both the “Group” documents at the top level and the “Person” documents that are populated will be lean.
|
|
When to Use Lean
When sending query results and are not modified and don’t use custom getters; it’s recommended to use lean()
. However, if the query results are modified or rely on features like getters or transforms, it’s better to avoid using lean().
e.g. returning a list of documents for GET
request
Useful Plugins
Using lean()
bypasses all Mongoose features, including virtuals, getters/setters,
and defaults. To use these features with lean()
, you need to use the corresponding plugin:
Conclusion
Lean is great for high-performance, read-only cases, especially when combined with cursors. With the help of plugins, lean()
can be used with virtuals, getters/setters, or defaults. The sample code is checked into mongoose-lean on github.
✨ Thank you for reading and I hope you find it helpful. I sincerely request for your feedback in the comment’s section.