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.
Query.prototype.lean()
// OR
query.lean([boolean])
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.
lean()
returns a JavaScript object instead of a Mongoose document.
In the code below, we create a Person
schema. We also make a query to return all the documents in the Person
collection. We then call the lean()
method on the query.
// 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.