2

In my Firebase database I have posts and then authenticated users can "like" posts. How can I efficiently get the number of likes a post has received. I know using MongoDB I can add/remove the user's id to a list and then use a MongoDB function to get the length of it very quickly and set that equal to the likes amount, but I'm not suer how to do that using Firebase. I could also add/remove it to the list and increment a likeCount variable, but that seems like it would cause concurrency issues unless Firebase has a function for that. What functions can I call to best handle this and scale well? Thanks in advance!

Big_Mac
  • 2,975
  • 4
  • 20
  • 36

1 Answers1

2

You can do both things:

1) Create a votes node with the UID as key and a value to sum up all the votes.

post:{
  //All the data
  likes:{
     $user_1:1,
     $user_2:-1,
  }
}

And then just get a SingleValue Event or a Value event(depending if you want to keep track of changes) and sum up all the children

2)You can use a transaction block and just save a value and increase or decrease it depending on the votes

(here is a link where you can find transactions for android,iOS or java) https://firebase.google.com/docs/database/web/save-data#save_data_as_transactions

 post:{
   //All the data,
   likes:2,
 }

It really depends on how much information you want to store, and what the user can do once he/she already voted for some post,

I would recommend using both, to keep flexibility for the user to like (like in Facebook) so he can unlike something and use the transaction with number to keep it scalable.. so if a post gets 1,000,000 likes you don't have to count the 1,000,000 likes every time someone loads the post

Ymmanuel
  • 2,523
  • 13
  • 12