anumi
anumi

Reputation: 3937

Relationships in MongoDB (via Mongoose)

Consider a typical blog application where a blog can have many posts and a post can have many comments. Assume we want to provide a RESTfull API to access it.

If I were to use a relational database to store this data, I would have a foreign key to a blog in the posts table and a foreign key to the post in the comments table.

When using MongoDB via Mongoose, I see three different ways to design the collections:

  1. Have three collections: one for blogs, one for posts and one for comments. The schema of posts would have a field referencing its blog and the the schema of comments would have a field referencing its post. (Very similar to the relational solution.)

  2. Again, three collections, but each blog would have an array of references to posts, and each post an array of references to comments.

  3. Just one collection with sub-documents and sub-sub-documents, where blogs contain an array of posts and each post contains an array of comments.

Which one is correct or, what are the pros and cons of each one?

Upvotes: 0

Views: 272

Answers (1)

Nuk Nuk San
Nuk Nuk San

Reputation: 560

How about the 3 collection approach, but

  1. Replicate last (N) comments into the Post collection with the $slice operator, thus keeping "latest comments" list short

  2. $inc a count of comments in the Post thus allowing quick retrieval of comment count per post

  3. Replicate or cache blog info from the Blog, or embed summary into the Post.

The main take home: Make it so that the Post entry contains all you want to render in one shot.

Upvotes: 1

Related Questions