What is the lean() method in Mongoose?

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 use lean() on a query.

Syntax

Query.prototype.lean()
// OR
query.lean([boolean])

Parameters

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.

Return value

lean() returns a JavaScript object instead of a Mongoose document.

Code

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 mongoose
const mongoose = require("mongoose");
// creating a Schema with mongoose
let Person = mongoose.model("Person", new mongoose.Schema({
name: String,
role: String
})
)
// make a query
const persons = await Person.find().lean();
// Check instance of document returned
docs[0] instanceof mongoose.Document; // false
docs[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.

Free Resources