Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Population and Relations

Populate Options and Nested Populate

Control Mongoose populate with select, match, sort, limit and perDocumentLimit, populate several paths, go several levels deep, and see how each option works in a runnable stand-in.

A bare populate('author') loads the entire author document. Real applications rarely want that: you want the name and avatar but not the password hash, only the published comments, only the latest five. Mongoose handles all of this through the populate options object, and through nesting for relations that are more than one hop long.

Everything here builds on References and populate(). The real API calls are shown read-only; the runnable examples reproduce each option with a small stand-in so you can see what the option does to the data.

The options object

Instead of a path string, pass an object. The most useful keys:

JavaScript
const posts = await Post.find().populate({
  path: 'author',
  select: 'name avatar -_id',   // field projection
  match: { active: true },      // filter the related docs
  options: { sort: { name: 1 }, limit: 5 },
});
  • path: the field to populate.
  • select: which fields of the related document to return (same syntax as Query#select).
  • match: a filter applied to the related query. Documents that do not match are replaced by null (single ref) or removed from the array.
  • options: query options such as sort, limit, skip.
  • model: force a model when the path has no ref or uses refPath.
  • populate: a nested populate, described below.

Strings also work for the simple case: .populate('author', 'name email') means path plus select.

select: keep secrets and weight out

Populating a whole user to show a name is wasteful, and dangerous if the user document contains a password hash. Always select.

Node.js select while populating (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A related trap: if you exclude _id from select and later try to populate again or match on it, you lose the join key. Exclude _id only for leaf output.

match is a filter on the related collection, not on the parent. Posts whose author does not satisfy the filter are still returned, with author: null. That surprises people who expected the posts to disappear. If you want to remove those posts, filter afterwards in JavaScript, or use an aggregation $lookup instead (see Aggregation: group and lookup).

Node.js match keeps the parent (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Arrays: limit, sort and perDocumentLimit

For an array of references (comments: [ObjectId]), options.limit applies to the whole second query, not to each post. With three posts and limit: 2 you may get two comments in total, not two per post. Use perDocumentLimit to limit per parent:

JavaScript
await Post.find().populate({
  path: 'comments',
  options: { sort: { createdAt: -1 } },
  perDocumentLimit: 2,
});

perDocumentLimit is implemented by running one query per parent document, so it trades the batching advantage for correct semantics. Use it only when the page needs it, and keep result sets small.

Node.js limit versus perDocumentLimit (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Several paths at once

Chain populate calls or pass a space-separated string or an array.

JavaScript
const posts = await Post.find()
  .populate('author', 'name')
  .populate('category', 'title slug');
// same as populate(['author', 'category']) when no options are needed

Each path costs one extra query. Two paths means three queries total. That is fine; ten paths usually means the schema wants some embedding.

Nested (multi-level) populate

To populate something on the populated document, use the populate key. Here a comment has an author, and the post has comments:

JavaScript
const post = await Post.findById(id).populate({
  path: 'comments',
  select: 'text author',
  populate: { path: 'author', select: 'name' },
});

The queries run in order: post, then comments, then comment authors. Three levels is already three round trips; deeper trees are a sign to reshape data or to fetch with an aggregation.

flowchart LR
  P["Post"] --> C["comments (query 2)"]
  C --> A["author (query 3)"]

Each level of nesting adds one query.

Node.js Nested populate (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Dynamic references: refPath

Sometimes a field can point at different models: a comment can belong to a Post or a Photo. Store the model name next to the id and tell Mongoose where to find it with refPath.

JavaScript
const commentSchema = new Schema({
  body: String,
  on: { type: Schema.Types.ObjectId, refPath: 'onModel' },
  onModel: { type: String, enum: ['Post', 'Photo'] },
});
await Comment.find().populate('on');

Mongoose groups the ids by model and runs one query per model.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a parent document when its populate match filter rejects the related document?

    match filters the related query only. Parents are still returned; use JavaScript or $lookup to drop them.
  2. 2. You need the latest 2 comments for EACH post in a list. Which option?

    limit applies to the whole batched query. perDocumentLimit applies per parent, at the cost of one query each.
  3. 3. How many queries does Post.findOne().populate({ path: 'comments', populate: 'author' }) run?

    Post, then comments, then authors: each level of populate adds one batched query.
  4. 4. Which key supports a reference that can point at more than one model?

    refPath names a sibling field holding the model name for each document.

Summary

  • Pass an options object to control select, match, options and nesting.
  • Always select the fields you need, never populate secrets.
  • match nulls out related documents but keeps the parents.
  • perDocumentLimit limits each parent's array; plain limit limits the whole query.
  • Nested populate adds one query per level; refPath supports multiple target models.

Next: Virtual populate