deno.land / x / mongoose@6.7.5 / docs / tutorials / lean.md

Faster Mongoose Queries With Lean

The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents. In this tutorial, you'll learn more about the tradeoffs of using lean().

Using Lean

By default, Mongoose queries return an instance of the Mongoose Document class. Documents are much heavier than vanilla JavaScript objects, because they have a lot of internal state for change tracking. Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document and just give you the POJO.

const leanDoc = await MyModel.findOne().lean();

How much smaller are lean documents? Here's a comparison.

[require:Lean Tutorial.*compare sizes]

Under the hood, after executing a query, Mongoose converts the query results from POJOs to Mongoose documents. If you turn on the lean option, Mongoose skips this step.

[require:Lean Tutorial.*compare types]

The downside of enabling lean is that lean docs don't have:

  • Change tracking
  • Casting and validation
  • Getters and setters
  • Virtuals
  • save()

For example, the following code sample shows that the Person model's getters and virtuals don't run if you enable lean.

[require:Lean Tutorial.*getters and virtuals]

Lean and Populate

Populate works with lean(). If you use both populate() and lean(), the lean option propagates to the populated documents as well. In the below example, both the top-level 'Group' documents and the populated 'Person' documents will be lean.

[require:Lean Tutorial.*conventional populate]

Virtual populate also works with lean.

[require:Lean Tutorial.*virtual populate]

When to Use Lean

If you're executing a query and sending the results without modification to, say, an Express response, you should use lean. In general, if you do not modify the query results and do not use custom getters, you should use lean(). If you modify the query results or rely on features like getters or transforms, you should not use lean().

Below is an example of an Express route that is a good candidate for lean(). This route does not modify the person doc and doesn't rely on any Mongoose-specific functionality.

// As long as you don't need any of the Person model's virtuals or getters,
// you can use `lean()`.
app.get('/person/:id', function(req, res) {
  Person.findOne({ _id: req.params.id }).lean().
    then(person => res.json({ person })).
    catch(error => res.json({ error: error.message }));
});

Below is an example of an Express route that should not use lean(). As a general rule of thumb, GET routes are good candidates for lean() in a RESTful API. On the other hand, PUT, POST, etc. routes generally should not use lean().

// This route should **not** use `lean()`, because lean means no `save()`.
app.put('/person/:id', function(req, res) {
  Person.findOne({ _id: req.params.id }).
    then(person => {
      assert.ok(person);
      Object.assign(person, req.body);
      return person.save();
    }).
    then(person => res.json({ person })).
    catch(error => res.json({ error: error.message }));
});

Remember that virtuals do not end up in lean() query results. Use the mongoose-lean-virtuals plugin to add virtuals to your lean query results.

Plugins

Using lean() bypasses all Mongoose features, including virtuals, getters/setters, and defaults. If you want to use these features with lean(), you need to use the corresponding plugin:

However, you need to keep in mind that Mongoose does not hydrate lean documents, so this will be a POJO in virtuals, getters, and default functions.

const schema = new Schema({ name: String });
schema.plugin(require('mongoose-lean-virtuals'));

schema.virtual('lowercase', function() {
  this instanceof mongoose.Document; // false

  this.name; // Works
  this.get('name'); // Crashes because `this` is not a Mongoose document.
});
mongoose

Version Info

Tagged at
a year ago