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() 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
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
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
lean() bypasses all Mongoose features, including virtuals, getters/setters,
and defaults. To use these features with
lean(), you need to use the corresponding plugin:
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.