Modeled MongoDB relationships with Mongoose, comparing when to embed vs reference and practicing populate() for stitched reads.
populate(): extra query to hydrate referenced docs—convenient, but avoid on hot paths.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);
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);
populate()const post = await Post.findOne().populate("author");
console.log(post.author.name);// hydrated author doc
populate() to pull author details alongside posts.