I want to create an app using MongoDB (NoSQL database) that allows people to vote on posts (simillar to Reddit). What's the recommended way to store votes for the users?
Probably the database structure will have to quickly respond to queries like:
Write:
- User X votes (up or down) post A.
Read:
- Has user X already voted for post A?
- How many votes (up-down) does post A have?
- Get posts ordered by vote count (top posts)
I was thinking about saving all the votes in the User document, so each user has a list of votes with the structure { voteID, postID, value }
, where value
can be 1
for upvote and -1
for downvote.
I read that this is fine because usually posts might have hundred of thousands of votes, but each user will usually have fewer votes than that, so votes are better distributed across the documents.
I was also thinking about caching the votes count per post, so have like a hook, each time a vote is added/removed the count for that specific document is also updated. One issue I see with this is if you ban/delete a user which has 10k votes, you will have to do 10k update operations on the posts to update the vote count.
What is the recommended way to store votes/likes in a NoSQL database?