Reputation: 974
I came up with multiple solutions but none of them seems to be "future proof".
Let me iterate my solutions first.
Acceptance criteria of the feature
Assumption
There is User collection and Post collection
1. Put array of user references who liked the post.
Problem
Super simple, but once "post" grows too much, all users that query the post will be affected. Also putting potentially infinite array in a document.
2. Put array of Post references to User
Problem
Same with above, but only the user with growing data may be affected.
3. Like schema with reference to User and Post and add counter to Post
Problem
This document will grow very rapidly, many users will like many posts everyday. How do I query which posts a user liked? What if this collection grows to millions of like documents?
So far I have not found the right answer, at first, I thought #1 was way to go, then quickly changed my mind to #3, then I was like - what if it grows fast and becomes painful to query to find "likes" from millions of documents every time I fetch posts? Now I am thinking #2 is "safer" option but I may be wrong. If I go #3, I'd like to separate /likes and/posts endpoints, so that's another issue. - how will I query if a user liked from list of posts? Should it be separate singular endpoint? But it will be too many calls each time list of posts loads up. I am confused :(
Thanks for reading.
Upvotes: 1
Views: 1006
Reputation: 1912
Door #3! Then your gonna use a unique compound index with User+Post to prevent duplicates and to have fast query times.
When you query posts your going to want to use an aggregate pipe so you can $lookup to see if the 'like' document exists for each post.
https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
https://docs.mongodb.com/manual/core/index-compound/index.html
Should get you started.
Upvotes: 2