0
0
MongodbHow-ToBeginner · 3 min read

How to Use lean() in Mongoose for Faster Queries

In Mongoose, use lean() after your query to get plain JavaScript objects instead of full Mongoose documents. This makes queries faster and uses less memory because it skips Mongoose's document methods and getters.
📐

Syntax

The lean() method is called on a Mongoose query to return plain JavaScript objects instead of Mongoose documents. It is used like this:

  • Model.find().lean()
  • Model.findOne().lean()
  • Model.findById().lean()

This tells Mongoose to skip creating full document instances and return simple objects.

javascript
Model.find(query).lean()
💻

Example

This example shows how to use lean() with a simple find() query. It fetches users as plain objects, which are faster to work with if you don't need Mongoose document features.

javascript
const mongoose = require('mongoose');

async function run() {
  await mongoose.connect('mongodb://localhost:27017/testdb');

  const userSchema = new mongoose.Schema({ name: String, age: Number });
  const User = mongoose.model('User', userSchema);

  // Insert sample data
  await User.create([{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]);

  // Query with lean()
  const users = await User.find().lean();

  console.log(users);

  await mongoose.connection.close();
}

run();
Output
[ { _id: ObjectId, name: 'Alice', age: 25, __v: 0 }, { _id: ObjectId, name: 'Bob', age: 30, __v: 0 } ]
⚠️

Common Pitfalls

One common mistake is using lean() when you need Mongoose document methods or virtuals, because lean() returns plain objects without those features. Another pitfall is forgetting to use lean() when you want faster read-only queries.

Also, lean() does not apply to update queries like findOneAndUpdate() unless you chain it properly.

javascript
/* Wrong: Trying to use document methods on lean result */
const user = await User.findOne({ name: 'Alice' }).lean();
console.log(user.save()); // Error: save is not a function

/* Right: Use lean only when you don't need document methods */
const userDoc = await User.findOne({ name: 'Alice' });
await userDoc.save(); // Works fine
📊

Quick Reference

MethodDescription
find().lean()Returns plain JS objects for multiple documents
findOne().lean()Returns a plain JS object for one document
findById().lean()Returns a plain JS object by ID
Without lean()Returns full Mongoose documents with methods
Use lean() forFaster read-only queries without document methods

Key Takeaways

Use lean() to get plain JavaScript objects instead of Mongoose documents for faster queries.
lean() skips Mongoose document methods and virtuals, so use it only when you don't need them.
Remember that lean() works with find queries but not with update queries unless chained properly.
Using lean() reduces memory usage and improves performance for read-only data retrieval.