Overview

Modeled MongoDB relationships with Mongoose, comparing when to embed vs reference and practicing populate() for stitched reads.

Cheat Sheet

Embedding Example (post with comments)

const commentSchema = new mongoose.Schema({
  text: String,
  author: String,
});

const postSchema = new mongoose.Schema({
  title: String,
  content: String,
  comments: [commentSchema],// embedded comments
});

const Post = mongoose.model("Post", postSchema);

Referencing Example (post with author)

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
});
const User = mongoose.model("User", userSchema);

const postSchema = new mongoose.Schema({
  title: String,
  content: String,
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
});
const Post = mongoose.model("Post", postSchema);

Hydrating References with populate()

const post = await Post.findOne().populate("author");
console.log(post.author.name);// hydrated author doc

What I Practiced

Trade-offs Noted

Next (Day 77)