Enabling Virtuals In Mongoose Lean Mode (in a FeathersJs service)
I’ve had some hard time when virtuals
wasn’t showing up. Without digging deep into Mongoose, I quickly turned lean
mode off, crafting a new technical debt. After a while, I decided to spend some to look into this particular issue.
(optional) A Quick Primer
This section is also available in my another article.
What is Lean mode in Mongoose?
When lean mode is enabled, all queries return plain JavaScript objects instead of Mongoose Document. In this case, Mongoose will never have to instantiate Mongoose Document from plain JS object, apply magic methods, etc. Neglecting all these overhead in Lean mode, it makes perfect sense to have lean enabled by default.
What is Virtual?
Virtuals are attributes derived during query, which the values are not actually persisted in MongoDB. Since virtual is one of Mongoose magic attributes, it is disabled by default.
Using The Mongoose Plugin— mongoose-lean-virtual
Thanks to the community, I discovered the official plugin — mongoose-lean-virtuals
, which supports virtuals which preserving the behavior of lean mode.