Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Population and Relations

References and populate()

Learn how Mongoose references work - ObjectId refs, populate(), what it really does behind the scenes, missing documents, and a runnable stand-in that shows the two-query join.

MongoDB has no JOIN. When a blog post belongs to an author, you have to decide where the author lives: copied into the post (embedding) or stored in its own collection with the post holding only an id (referencing). Mongoose gives the second option a friendly face called population: you store an ObjectId in one document and ask Mongoose to swap it for the real document when you read.

This lesson explains how references are declared, what populate() really does (it is not a database join), and how to reason about its cost. You will also run a small stand-in that performs the same two-step lookup with plain JavaScript.

The Mongoose package and a MongoDB server cannot run on this site. The real Mongoose code in this chapter is read-only; every runnable example uses a small hand-written in-memory stand-in that mimics the behavior and says so. The stand-ins teach the idea, not the exact API.

Declaring a reference

A reference is a schema path of type ObjectId with a ref option naming the model it points at. The name is the string you passed to mongoose.model().

JavaScript
import mongoose from 'mongoose';
const { Schema, model } = mongoose;

const userSchema = new Schema({ name: String, email: String });
const postSchema = new Schema({
  title: String,
  author: { type: Schema.Types.ObjectId, ref: 'User' },
});

const User = model('User', userSchema);
const Post = model('Post', postSchema);

In MongoDB the stored post looks like { _id: ..., title: 'Hello', author: ObjectId('65f...') }. Only the id is saved, so renaming a user later changes nothing in the posts. This is the heart of the trade-off: no duplicated data, but one more lookup when you need the author's name. See Embedding or referencing for when each side wins.

Calling populate()

JavaScript
const post = await Post.findOne({ title: 'Hello' }).populate('author');
console.log(post.author.name); // 'Ada'

Without .populate('author'), post.author is just an ObjectId. With it, Mongoose runs the post query first, collects the ids found in author, runs a second query User.find({ _id: { $in: [...] } }), and then stitches the results into place. For a list of 50 posts there are still only two queries, not 51: Mongoose batches the ids. That is the difference between populate and an N+1 loop you write by hand.

sequenceDiagram
  participant App
  participant Mongoose
  participant DB as MongoDB
  App->>Mongoose: Post.find().populate("author")
  Mongoose->>DB: query 1 - find posts
  DB-->>Mongoose: posts with author ids
  Mongoose->>DB: query 2 - find users with _id in [ids]
  DB-->>Mongoose: users
  Mongoose-->>App: posts with author documents

Populate is two round trips, merged on the client.

A runnable stand-in

This stand-in keeps two arrays and a populate helper that does exactly the two steps above. It also counts "queries" so you can see that the number does not grow with the number of posts.

Node.js Populate as two queries (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.

Three posts, two queries. Add a thousand posts and the count stays two; only the size of the second query's $in list changes.

What happens to missing documents

If a post points at a user that was deleted, nothing breaks loudly: the populated field becomes null (for a single reference) or the id is dropped from the array (for an array of references). MongoDB has no foreign-key constraint, so you are responsible for cleanup, usually in a post('deleteOne') hook (Mongoose middleware) or by never hard-deleting referenced documents.

Node.js Dangling references (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 of references

A path can hold many ids: comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]. Populating that path replaces each id with its document, preserving the order of the stored array. Keep such arrays small. An unbounded array (every follower of a celebrity) makes the parent document grow toward the 16 MB limit; in that case store the reference on the child instead and use virtual populate.

Reading the result: documents and lean

A populated field is a full Mongoose document, with its own getters, virtuals and methods. If you only need data to send as JSON, add .lean() to the query; populated fields then come back as plain objects, which is faster and uses less memory (more in Lean, select and pagination).

JavaScript
const plain = await Post.find().populate('author').lean();

You can also populate after the fact: await post.populate('author') on an existing document, or await Post.populate(posts, 'author') on an array you already have.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many queries does Post.find().populate('author') run for 100 posts?

    Mongoose collects every author id and fetches them with one $in query, so the count does not grow with the number of posts.
  2. 2. What does a populated single reference become if the target document no longer exists?

    MongoDB has no foreign keys, so Mongoose simply puts null where the missing document would be.
  3. 3. What goes in the ref option?

    ref names the registered model, such as 'User'. Mongoose finds the collection from that model.
  4. 4. Why is populate not a real JOIN?

    The merge happens client side after a second query; nothing is stored in the parent beyond the id.

Summary

  • A reference is an ObjectId path with ref: 'ModelName'.
  • populate() runs a second batched query and merges the result in your app.
  • It costs a round trip, so populate only the paths you need.
  • Dangling references become null; cleanup is your job.
  • Use .lean() when you only need plain data.

Next: Populate options and nested populate