Faster Mongoose Queries With Lean

Sponsor #native_company# — #native_desc#

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.

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

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

  1. const schema = new mongoose.Schema({ name: String });
  2. const MyModel = mongoose.model('Test', schema);
  3. await MyModel.create({ name: 'test' });
  4. // Module that estimates the size of an object in memory
  5. const sizeof = require('object-sizeof');
  6. const normalDoc = await MyModel.findOne();
  7. // To enable the `lean` option for a query, use the `lean()` function.
  8. const leanDoc = await MyModel.findOne().lean();
  9. sizeof(normalDoc); // >= 1000
  10. sizeof(leanDoc); // 86, 10x smaller!
  11. // In case you were wondering, the JSON form of a Mongoose doc is the same
  12. // as the POJO. This additional memory only affects how much memory your
  13. // Node.js process uses, not how much data is sent over the network.
  14. JSON.stringify(normalDoc).length === JSON.stringify(leanDoc.length); // true

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.

  1. const normalDoc = await MyModel.findOne();
  2. const leanDoc = await MyModel.findOne().lean();
  3. normalDoc instanceof mongoose.Document; // true
  4. normalDoc.constructor.name; // 'model'
  5. leanDoc instanceof mongoose.Document; // false
  6. leanDoc.constructor.name; // 'Object'

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.

  1. // Define a `Person` model. Schema has 2 custom getters and a `fullName`
  2. // virtual. Neither the getters nor the virtuals will run if lean is enabled.
  3. const personSchema = new mongoose.Schema({
  4. firstName: {
  5. type: String,
  6. get: capitalizeFirstLetter
  7. },
  8. lastName: {
  9. type: String,
  10. get: capitalizeFirstLetter
  11. }
  12. });
  13. personSchema.virtual('fullName').get(function() {
  14. return `${this.firstName} ${this.lastName}`;
  15. });
  16. function capitalizeFirstLetter(v) {
  17. // Convert 'bob' -> 'Bob'
  18. return v.charAt(0).toUpperCase() + v.substr(1);
  19. }
  20. const Person = mongoose.model('Person', personSchema);
  21. // Create a doc and load it as a lean doc
  22. await Person.create({ firstName: 'benjamin', lastName: 'sisko' });
  23. const normalDoc = await Person.findOne();
  24. const leanDoc = await Person.findOne().lean();
  25. normalDoc.fullName; // 'Benjamin Sisko'
  26. normalDoc.firstName; // 'Benjamin', because of `capitalizeFirstLetter()`
  27. normalDoc.lastName; // 'Sisko', because of `capitalizeFirstLetter()`
  28. leanDoc.fullName; // undefined
  29. leanDoc.firstName; // 'benjamin', custom getter doesn't run
  30. leanDoc.lastName; // 'sisko', custom getter doesn't run

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.

  1. // Create models
  2. const Group = mongoose.model('Group', new mongoose.Schema({
  3. name: String,
  4. members: [{ type: mongoose.ObjectId, ref: 'Person' }]
  5. }));
  6. const Person = mongoose.model('Person', new mongoose.Schema({
  7. name: String
  8. }));
  9. // Initialize data
  10. const people = await Person.create([
  11. { name: 'Benjamin Sisko' },
  12. { name: 'Kira Nerys' }
  13. ]);
  14. await Group.create({
  15. name: 'Star Trek: Deep Space Nine Characters',
  16. members: people.map(p => p._id)
  17. });
  18. // Execute a lean query
  19. const group = await Group.findOne().lean().populate('members');
  20. group.members[0].name; // 'Benjamin Sisko'
  21. group.members[1].name; // 'Kira Nerys'
  22. // Both the `group` and the populated `members` are lean.
  23. group instanceof mongoose.Document; // false
  24. group.members[0] instanceof mongoose.Document; // false
  25. group.members[1] instanceof mongoose.Document; // false

Virtual populate also works with lean.

  1. // Create models
  2. const groupSchema = new mongoose.Schema({ name: String });
  3. groupSchema.virtual('members', {
  4. ref: 'Person',
  5. localField: '_id',
  6. foreignField: 'groupId'
  7. });
  8. const Group = mongoose.model('Group', groupSchema);
  9. const Person = mongoose.model('Person', new mongoose.Schema({
  10. name: String,
  11. groupId: mongoose.ObjectId
  12. }));
  13. // Initialize data
  14. const g = await Group.create({ name: 'DS9 Characters' });
  15. const people = await Person.create([
  16. { name: 'Benjamin Sisko', groupId: g._id },
  17. { name: 'Kira Nerys', groupId: g._id }
  18. ]);
  19. // Execute a lean query
  20. const group = await Group.findOne().lean().populate({
  21. path: 'members',
  22. options: { sort: { name: 1 } }
  23. });
  24. group.members[0].name; // 'Benjamin Sisko'
  25. group.members[1].name; // 'Kira Nerys'
  26. // Both the `group` and the populated `members` are lean.
  27. group instanceof mongoose.Document; // false
  28. group.members[0] instanceof mongoose.Document; // false
  29. group.members[1] instanceof mongoose.Document; // false

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.

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

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().

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

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.

  1. const schema = new Schema({ name: String });
  2. schema.plugin(require('mongoose-lean-virtuals'));
  3. schema.virtual('lowercase', function() {
  4. this instanceof mongoose.Document; // false
  5. this.name; // Works
  6. this.get('name'); // Crashes because `this` is not a Mongoose document.
  7. });