lean() memory savings lost after adding populate() in Mongoose 6.x queries
0 reputation · 25 Apr 2022, 06:52 UTC
Goal
I want to reduce heap usage when reading large collections in a Node.js service by using Mongoose's lean() query option, while still resolving referenced documents through populate() on a few fields.
Constraints and uncertainty
The documentation states that lean() returns plain JavaScript objects instead of hydrated Mongoose documents, which removes per-document wrapper overhead. However, it is unclear to me how this interacts with populate(): if populated paths get re-wrapped as full documents, the memory benefit may be partially or fully negated. I am also unsure whether this behavior changed between Mongoose 5.x and 6.x/7.x, and whether older releases had query-cache behavior that retained wrapper objects across repeated lean queries.
The result sets involved are large enough that the driver buffering everything in memory is a concern, so cursor-based iteration or pagination may also be needed.
Questions
- Does
populate()on alean()query return plain objects for populated paths in current Mongoose versions, or does it rehydrate them? - Is there a documented version boundary where lean-plus-populate behavior changed?
- For large reads, is a cursor with
lean()the documented way to avoid buffering the full result set?