I am curious to know what the benefit of not using .lean() on a Mongoose query is. What does the extra overhead in the Mongoose response actually allow you to do?
I find it makes it so hard to work with the documents return as as objects unless I use the .lean() method on the query.
Am I missing something? Are there a tonne of unexplored benefits that I'm losing by stripping the Mongoose documents down before I use them in my application?
I haven't exactly tested but this ARTICLE BY SAKSHI TYAGI does a good job comparing the execution time of a mongoose query without and with the .lean() method which clearly shows that one without it takes almost 3x that with a .lean() method. The article attributed this to the fact that the .lean() method only returns a javascript object and by so doing strips of all "moongoose magic" as well as methods (including save etc) and getters/setters.
I on one hand would say that it helps to quickly add new fields to the return object before sending response to users easily as below;
.then(result=>{
result.something = "another thing";
return res.json(result);
})
Note that a query without the .lean() doesn't return a javascript object and so you would need to convert the result to a javascript object before using the syntax to add new fields to the object or even delete like below;
.then(result=>{
result = result.toObject();
delete result.something;
return res.json(result);
})
You can find the above information backed on this mongoose doc page as it quotes "This is a great option in high-performance read-only scenarios, especially when combined with stream.".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With