Sequence NODE_280
Medium

Model One-to-Many Comments for a Post

MongoDB
Technical Specification

Design how to store comments for posts: either embedded array of comments or separate comments collection with postId, and explain tradeoffs.

Input/Output Samples
Input:post with 3 comments
Output:Either embedded or referenced structure
Optimal Logic Path
// Embedded example:
{
  _id: ObjectId("post1"),
  title: "Post title",
  comments: [
    { _id: ObjectId(), text: "Nice", authorId: ObjectId("user1"), createdAt: new Date() },
    { _id: ObjectId(), text: "Great", authorId: ObjectId("user2"), createdAt: new Date() },
  ],
}

// Referenced example:
{
  _id: ObjectId("comment1"),
  postId: ObjectId("post1"),
  text: "Nice",
  authorId: ObjectId("user1"),
  createdAt: new Date(),
}
Architectural Deep-Dive
Embedding simplifies reads but can cause large documents; separate collection scales better for many comments.