Mongoose & the Full StackPro· 35 min read

Relationships & populate

Connect documents across collections — like posts to their authors — and pull them together with populate.

What you will learn

  • Reference one document from another
  • Use populate to join data
  • Decide between referencing and embedding

Referencing other documents

Real data is connected: a post has an author, an order has a customer. Store the related document’s _id as a reference.

A Post that references a User
const postSchema = new mongoose.Schema({
  title: String,
  body: String,
  author: { type: mongoose.Schema.Types.ObjectId, ref: "User" }
});

The author field does not store the whole user — it stores that user’s _id. The type mongoose.Schema.Types.ObjectId says “this holds an id”, and ref: "User" tells Mongoose which collection that id points to (the User model). It is like saving a friend’s phone number instead of writing out their entire contact card each time.

populate — pull in the related data

populate replaces the stored _id with the actual referenced document when you query.

populate joins the referenced data
// Without populate: author is just an id
// With populate: author becomes the full user document
const posts = await Post.find().populate("author");
// posts[0].author.name now works

Normally a post’s author comes back as just an id — not very useful on its own. Adding .populate("author") tells Mongoose to follow that id into the User collection and swap it for the whole user document. That is why posts[0].author.name suddenly works: author is now a full object, not a bare id.

Note: Output: Without populate → author: ObjectId('65f...u1') With populate → author: { _id: '65f...u1', name: 'Asha', email: 'asha@x.com' } Same query, but populate pulls the related user in so you can read its fields directly — just like a join in SQL.

Note: Reference (store an id) when data is shared or large; embed (nest the object) when data belongs only to its parent and is read together. Choosing well is a key data-modelling skill.

Q. What does Mongoose populate() do?

Answer: populate() follows a reference (stored _id) and replaces it with the full referenced document — like a join.

✍️ Practice

  1. Create User and Post models where a post references a user.
  2. Query posts with populate("author") and read the author’s name.

🏠 Homework

  1. Model a blog with users, posts and comments using references, and populate them.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →