When documents are queried, they are returned as Mongoose Documents by default. With the Mongoose lean()
method, the documents are returned as plain objects.
The only challenge here is that you are not able to use Mongoose features such as
save()
, virtuals, getters, etc., if you uselean()
on a query.
The method accepts an optional boolean
value that can be true
or false
. The lean()
method assumes it to be true
by default if no parameter is provided.
// import mongooseconst mongoose = require("mongoose");// creating a Schema with mongooselet Person = mongoose.model("Person", new mongoose.Schema({name: String,role: String}))// make a queryconst persons = await Person.find().lean();// Check instance of document returneddocs[0] instanceof mongoose.Document; // falsedocs[0] instanceof Object // true
In the code above, we can use the instanceof()
method to check the type of the returned document, which is a plain JavaScript object.