Skip to content

Instantly share code, notes, and snippets.

@muslemomar
Last active May 26, 2022 13:40
Show Gist options
  • Save muslemomar/d6577e56f1100c35093b154374678c85 to your computer and use it in GitHub Desktop.
Save muslemomar/d6577e56f1100c35093b154374678c85 to your computer and use it in GitHub Desktop.
Comparison of putting author inside blogpost vs blogpost inside author

1. Embedding BlogPosts inside Author:

AuthorSchema = { blogposts: BlogPost[] }

✔ Pros:

  • Easy to query for all/specific authors.
  • Easy to update an author or delete him (including his blogposts) with a single command.
  • No matter the number of authors you have, it won't impact on the query speed.
  • Retrieve the author and all of his blogposts using a single command.

❌ Cons:

  • Difficulty querying/filtering for certain blogposts since they're embedded inside another document (nested).
  • Whenever we want to get the posts, we'd have to get the authors too, even though we're not requiring them.
  • Since so many blogposts will be created, blogposts field will grow larger and eventually reach Mongodb document max size (16mb).
  • Not possible to implement pagination on blogposts.

2. Embedding Author inside Blogposts :

BlogPostSchema = { author: Author }

✔ Pros:

  • Retrieve all blogposts using a single command.
  • Query Efficiency: Easy to filter for blogposts.
  • Storage Efficiency: We could create as many blogposts as we want (without hitting document max size limit).
  • Easily implement pagination on blogposts.

❌ Cons:

  • Data Redundancy: Authors would be repeated across multiple blogposts, if they have multiple blogposts.
  • To update/delete a single author, we'd have to update/delete all of his instances through all of his blogposts.
  • Not possible to implement pagination on authors.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment