[Mongoose] When lean option is enabled, a plain javascript object is returned instead of MongooseDocument
As the title says, when you enable the lean option in Mongoose, a plain javascript object is returned instead of a MongooseDocument.
Documents returned from queries with the lean option enabled are plain javascript objects, not MongooseDocuments. They have no save method, getters/setters or other Mongoose magic applied.
Since they are not Mongoose documents, convenient features unique to Mongoose like the save method, virtual getters/setters, and instance methods are no longer available.
(Example) Query using lean option
new Query().lean() // true
new Query().lean(true)
new Query().lean(false)
Model.find().lean().exec(function (err, docs) {
docs[0] instanceof mongoose.Document // false
});
I had trouble in my work when I enabled the lean option. There was a section that used virtuals on populated documents, and that part stopped working.
As a fix strategy, I implemented a method that takes plain js objects as arguments instead of using virtuals, and modified the code to use that.
You probably won’t use the lean option unless you’re in a situation where you need to do performance tuning, but when that time comes, it might be good to carefully check that existing processes that use Mongoose features aren’t broken.
That’s all from the Gemba.