skip to content

In Mongoose 9, what does calling lean() on a query give up, and when is it the right choice for a read endpoint?

level: middleimportance: should knowfreq 50%

answer

  1. hydration skipped
  2. plain objects out
  3. no virtuals, getters, save()
  4. schema toJSON transform skipped
  5. filter is still cast

basics

~20 s

lean() tells Mongoose to skip hydrating results into documents and return plain objects: less memory and CPU, but no change tracking, save(), getters, setters, virtuals (including id), load-time defaults or schema toJSON transforms. Use it for read-only responses.

solid answer

~40 s

By default a query result is **hydrated**: Mongoose wraps each raw object in a document with change tracking, getters, setters, virtuals and `save()`. `Model.find().lean()` skips that step and resolves to plain objects, which the docs measure at roughly a third of the in-process size. What you lose is everything the document class adds: no `save()`, no virtuals such as `id`, no custom getters, no defaults filled in for older documents, and no schema-level `toJSON` transform, so a transform that hides `passwordHash` does not run. What stays: the **filter** is still cast and the projection still applies, including `select: false`, and `lean` carries over to populated paths. Use it on read paths that send data straight to the client; keep full documents when you will modify and save, or rely on virtuals, getters or transforms.

code

javascript · 27 lines
javascript
import mongoose from 'mongoose';

const userSchema = new mongoose.Schema(
  {
    email: String,
    passwordHash: String,
    plan: { type: String, default: 'free' }
  },
  { toJSON: { transform(doc, ret) { delete ret.passwordHash; return ret; } } }
);
const User = mongoose.model('User', userSchema);

// Route handlers; `res` is the framework's response object
export async function listHydrated(req, res) {
  // toJSON transform runs inside res.json(); plan defaults to 'free'
  res.json(await User.find());
}

export async function listLeanUnsafe(req, res) {
  // Plain objects: passwordHash IS sent, and older documents lack plan
  res.json(await User.find().lean());
}

export async function listLeanSafe(req, res) {
  // The projection removes the field before it leaves the server
  res.json(await User.find().select('-passwordHash').lean());
}

go deeper

for a junior

Recall that lean() returns plain objects instead of Mongoose documents and that you cannot call save() on them.

for a middle

Explain hydration and list exactly what lean drops: change tracking, getters, setters, virtuals, load-time defaults and transforms, and what it keeps: filter casting, projection and populate.

for a senior

Catch the behaviour changes before switching an endpoint: a transform-hidden field leaking, id vanishing for the client, defaults missing on old documents. Hide sensitive paths with projection so lean is safe.

for a principal

Set a convention for read paths, such as lean by default for GET handlers plus select: false on sensitive paths, and decide where computed fields live once virtuals are no longer applied automatically.

## What hydration is The MongoDB driver returns each result as a plain JavaScript object (a POJO). Before handing it to you, Mongoose normally **hydrates** it: it constructs an instance of your model, runs `init`, records which paths exist so it can track changes, applies defaults for missing paths, and wires up getters, setters and virtuals. That is what makes `doc.status = 'paid'; await doc.save()` work. `lean()` is a Query option that skips that step. `await Order.find({ status: 'paid' }).lean()` resolves to the raw objects. The Mongoose lean tutorial measures a hydrated document at about three times the in-process size of the lean one, while the JSON sent over the network is the same. On a list endpoint that returns hundreds of documents, skipping hydration saves both memory and CPU. ## What lean() keeps and what it drops | Feature | Hydrated document | `lean()` result | |---|---|---| | Filter casting (`'64b7...'` to `ObjectId`) | yes | yes, it happens before the query runs | | Projection and `select: false` paths | applied | applied | | `populate()` | documents | plain objects, lean propagates | | Change tracking and `save()` | yes | no | | Custom getters and setters | run | do not run | | Virtuals, including `id` | present | absent | | Defaults for paths missing in stored data | applied on load | absent | | Schema `toJSON` / `toObject` transforms | applied when the document is serialised | not applied | | `post('init')` hooks | run | do not run, nothing is initialised | | `instanceof mongoose.Document` | `true` | `false` | The first rows are the ones people get wrong in the other direction: `lean()` is not "raw driver mode". The filter is still cast against the schema, query middleware such as `pre('find')` still runs, and the projection the schema asks for still applies. ## When lean() is the right call The Mongoose docs give a simple rule: if you send the results to the client without modifying them and do not rely on getters, virtuals or transforms, use `lean()`. In practice: - **Good fit:** `GET` endpoints that list or show records, exports, reports and background jobs that only read. - **Poor fit:** handlers that load, change and `save()`, because a lean result has no `save()`. - **Poor fit:** read paths whose response shape depends on virtuals (a computed `displayName`), getters (a currency path stored in cents and formatted on read) or a `toJSON` transform. ## The traps Switching an existing endpoint to `lean()` changes its output in ways that tests often miss: 1. **Hidden fields reappear.** If a User schema hides `passwordHash` with a `toJSON` transform, `res.json(await User.find().lean())` now sends the hash, because there is no document whose `toJSON()` could run. Hide sensitive paths with `select: false` or an explicit projection, which lean results respect. 2. **`id` disappears.** The `id` string is a virtual. A front end that reads `order.id` gets `undefined` and must use `_id`. 3. **Old documents lose defaults.** A path added to the schema later with a `default` shows that default on hydrated documents but is simply missing on lean ones. 4. **Getter output changes.** A value that a getter formats on read comes back in its stored form. 5. **Code that calls document methods breaks.** `doc.populated()`, `doc.toObject()` and `doc.save()` do not exist on a POJO. The Mongoose docs point to plugins that restore virtuals, getters or defaults on lean results; inside them `this` is a POJO, not a document. ## lean() with populate When a query uses both, `lean` propagates: `await Order.find().lean().populate('user')` returns plain orders whose `user` values are plain objects too. That makes `lean()` a natural pair with populate on list endpoints, and the trade-offs above apply to every populated object as well. ## A checklist before switching an endpoint - Search the handler and its serializer for virtuals, getters and `toJSON` options the response relies on. - Move field hiding into the query with `select: false` or `.select()`, so it holds for lean and hydrated reads alike. - Check what the client reads: `id` versus `_id`, formatted versus stored values, and fields that only exist as defaults. - Keep handlers that modify and `save()` on hydrated documents. - Compare the response before and after in a test, because a missing virtual fails silently rather than throwing.

  • Does a Mongoose query with lean() still throw a CastError for a malformed id?
    Yes. `lean()` only changes what Mongoose does with the results. The filter is cast when the query executes, so `User.findById('nope').lean()` still rejects with a `CastError` and a valid hex string is still converted to an `ObjectId`. That is the difference from `Model.aggregate()`, which casts nothing.
  • How do you hide a sensitive field reliably on both hydrated and lean reads?
    Exclude it in the query rather than at serialisation time: mark the path `select: false` in the schema, or project it away with `.select('-passwordHash')`. The projection is applied by the server, so the value never reaches your process, and it holds for `lean()` results, populated documents and hydrated documents alike.

A hydrated document is the live form in an office system, with spell-check, computed totals and a submit button; a lean result is a photocopy of the same form. The photocopy is lighter to carry around, but nothing on it recalculates, and any redaction the system applied when printing is missing.

  • lean() returns the raw driver result, so the filter is not cast.
  • A schema toJSON transform still hides fields on lean results.
  • Lean results still have the id virtual, so front ends can keep using it.
  • You can edit a lean result and call save() as usual.
  • lean() makes the server send fewer bytes over the network.