Mongoose list endpoint is slow: how to tell hydration overhead from a bad query plan before adopting lean()
0 reputation · 24 Oct 2024, 06:57 UTC
On a read-heavy Mongoose list endpoint (assume Mongoose 7/8, Node 18+, MongoDB 6), the plan is to measure before optimizing. The candidate lever is the documented query.lean() option, which returns plain JavaScript objects instead of hydrated documents, skipping change tracking, getters, and middleware state. But that only helps if request time is dominated by client-side document instantiation rather than server-side work.
The uncertainty is twofold. First, how to attribute latency correctly: explain() on the underlying MongoDB query shows index usage and collection scans, while a benchmark timing the same query with and without .lean() at realistic result sizes shows hydration cost — but it is unclear which measurement should gate the decision, and at what result-set size lean() typically becomes worthwhile. Second, the adoption strategy: enabling lean() per query versus globally via a plugin changes the contract for every downstream consumer, since lean results lose instance methods, virtuals, and save().
What is a reliable way to separate hydration overhead from query-plan problems in profiling? Is there a documented or conventional threshold for when lean() pays off? And is global lean-by-default considered safe practice, or should it stay opt-in per query?