Stop 07 · Mongoose ODMTopics · 5/8

Populate for References

Part of the MERN Stack Roadmap

In short

A post stores its author as an ObjectId, but the React page needs the author's name and photo. populate() swaps the id for the real user document, so you don't write a second query by hand.

When a field stores an ObjectId with ref: 'User', populate() replaces it with the referenced document in the query result, so you can return a post with its author's name.

The jaadu hands a small numbered token across a cloakroom counter and receives a colourful bag in return, with rows of hanging bags behind.

Think of it like this

The cloakroom token

At a wedding hall you leave your bag and get a numbered token. The token is small and easy to carry, like an ObjectId. When you need the bag, you hand in the token and get the real thing back. populate() hands in the tokens for you.

Watch it happen

Post.find().populate("author", "name avatar")

title: Exam Tips
0
author: 665f...a1
1
likes: 42
2

1/3Stored in MongoDB, author is just an ObjectId.

The big ideas

What you need to know

ref tells Mongoose where to look

author: { type: Schema.Types.ObjectId, ref: "User" } links the field to the User model.

Select fields

populate("author", "name avatar") fetches only what the page shows. Never send password hashes.

Nested populate

populate({ path: "comments", populate: { path: "author", select: "name" } }) goes two levels deep.

It's an extra query

populate runs a separate query per path, not a database join. For heavy reports, use $lookup instead.

See it in code

Walk through the code

js
1const postSchema = new Schema(2  {3    title: { type: String, required: true },4    body: String,5    author: { type: Schema.Types.ObjectId, ref: "User", required: true },6    tags: [String],7  },8  { timestamps: true }9);10export const Post = model("Post", postSchema);11 12// GET /api/posts13const posts = await Post.find({ tags: "exams" })14  .sort({ createdAt: -1 })15  .limit(10)16  .populate("author", "name avatar")17  .lean();18 19// GET /api/posts/:id with comments and their authors20const post = await Post.findById(id).populate("author", "name").lean();21const comments = await Comment.find({ post: id })22  .populate({ path: "author", select: "name avatar" })23  .lean();

1/5Store the author as an ObjectId that refers to the User model.

The id lives in MongoDB. populate fills it in only in the response.

Save yourself the pain

Common mistakes

Oops

populate("author") with no field list, sending the whole user including the password hash.

Do this instead

Always pass the fields you need, and mark password with select: false in the schema.

Oops

Populating inside a loop, one post at a time.

Do this instead

Call populate on the query. Mongoose batches all ids into a single query per path.

Your mission

Posts with authors

~25 min

Quick check

What does populate() do with an author ObjectId in a query result?

Go deeper

  1. 1Populate the author on a list of posts and select only name and avatar.
  2. 2Populate a nested path, such as comments and their authors.
  3. 3Watch for many populates on one request, which mean many extra queries.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge