Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท Population and Relations

Virtual Populate for Reverse Relations

Learn Mongoose virtual populate - define a reverse relation with localField and foreignField, avoid unbounded arrays of ids, count related documents, and see it in a runnable stand-in.

Suppose a blog has authors and posts. Each post stores its author id. Now you want an author page that lists their posts. The data model already supports that, since the posts know their author, but the author document knows nothing about its posts. The old fix was to also store posts: [ObjectId] on the author and keep both sides in sync. That doubles your writes and the array grows without limit.

Virtual populate solves this: you declare a virtual property on the parent that tells Mongoose how to find the children by matching a field, and nothing extra is stored.

Defining a virtual populate

A virtual populate needs four pieces of information: the model to look in (ref), the field on the parent that holds the key (localField), the field on the child that holds the same key (foreignField), and whether you expect one or many results (justOne).

JavaScript
const authorSchema = new Schema(
  { name: String },
  { toJSON: { virtuals: true }, toObject: { virtuals: true } },
);

authorSchema.virtual('posts', {
  ref: 'Post',
  localField: '_id',
  foreignField: 'author',
});

const Author = model('Author', authorSchema);

const ada = await Author.findOne({ name: 'Ada' }).populate('posts');
console.log(ada.posts.length);

The posts virtual is not saved to MongoDB. It only exists in memory after you call populate('posts'). Without populate it is undefined. Remember the toJSON/toObject options: virtuals are left out of JSON output unless you enable them, which is the most common reason a "working" virtual populate seems empty in an API response.

What Mongoose does

It reads localField from each parent, then queries Post.find({ author: { $in: [parentIds] } }), and attaches the matching children to the right parent. The relation is defined on the side where nothing is stored, so deleting or adding a post never requires editing the author.

Node.js A reverse lookup (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.

Why it beats an array of ids

Approach Stored data Writes per new post Growth
posts: [ObjectId] on author ids on both sides 2 (post + author) author document grows forever
Virtual populate id on the post only 1 none

The array approach can drift out of sync if one write succeeds and the other fails, and a very popular author can hit the 16 MB document limit. Virtual populate has neither problem. The price is that you need an index on the child's foreign field: postSchema.index({ author: 1 }), or the second query scans the collection (see Indexes in Mongoose).

justOne: a reverse one-to-one

When each parent has at most one child, use justOne: true. The virtual then returns a single document or null instead of an array.

JavaScript
userSchema.virtual('profile', {
  ref: 'Profile',
  localField: '_id',
  foreignField: 'user',
  justOne: true,
});

Counting without loading

If you only need how many children exist, add count: true. Mongoose runs a count query per the matching rules and returns a number, not the documents.

JavaScript
authorSchema.virtual('postCount', {
  ref: 'Post',
  localField: '_id',
  foreignField: 'author',
  count: true,
});
const a = await Author.findOne().populate('postCount');
console.log(a.postCount); // 3
Node.js Counting related documents (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.

Options you can pass at populate time

Virtual populate accepts the same options as normal populate: select, match, options (sort, limit) and nested populate. Since the children live in their own collection, perDocumentLimit is again the way to get "latest three posts per author":

JavaScript
await Author.find().populate({
  path: 'posts',
  select: 'title createdAt',
  options: { sort: { createdAt: -1 } },
  perDocumentLimit: 3,
});

You can also set options: { sort, limit } directly in the virtual definition as a default, then override it per query.

Limits to remember

  • A virtual populate works only on documents found by a query (or populated on an existing document). You cannot query by a virtual: Author.find({ posts: ... }) does nothing useful, because the data is not in the author collection. Query the child collection or use an aggregation $lookup.
  • lean() skips virtuals by default, but virtual populate still works with lean; the result is plain objects. Other virtuals (getters) need the mongoose-lean-virtuals plugin.
  • The localField does not have to be _id. Any shared key works, for example a slug or employeeNumber.
flowchart LR
  A["Author (no posts field stored)"] -- "_id = author" --> P["Post documents"]

The relation is computed at read time from the child's reference.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a virtual populate store in MongoDB?

    The virtual exists only in memory after populate; the only stored link is the child's own reference field.
  2. 2. Which pair of options links a parent to its children?

    localField is the key on the parent, foreignField is the matching key on the child (plus ref for the model).
  3. 3. Your API response from a virtual populate is missing the posts. What is the likely cause?

    Set toJSON: { virtuals: true } (and toObject) on the schema so virtual values are serialized.
  4. 4. How do you get only the number of related documents?

    count: true makes populate run a count and return a number.

Summary

  • Virtual populate defines a reverse relation with ref, localField and foreignField.
  • Nothing is stored on the parent, so there is no sync problem and no unbounded array.
  • Use justOne for single results and count for counts.
  • Index the child's foreign field, and enable virtuals in toJSON.
  • You cannot filter parents by a virtual; use aggregation for that.

Next: Embedding or referencing