google-cloud-firestorevote

Most efficient voting system in Firebase


I'm working on an app that lets users upload pictures and rate (so vote with stars 1-5) each others pictures. But I keep thinking that the database system that I'm building is not efficient enough. I hope that there is someone who can give me advice.

Right now I have a database table called "images". It has the following fields:

Everytime a user votes the amount_of_votes gets a +1 and the rating gets calculated by (rating*old amount of votes + new vote) / new amount of votes

But this gives me the following problems:

I want to build a new voting system where there is a new table called votes and it holds the user_id and the vote that the user gives. But that gives me the following problem:

Does anyone know what the best system is that I can use? I have spend days on the internet but I haven't found the best system yet...


Solution

  • I didn’t try implementing it myself but my approach for this will be the use of a Snapshot listener.

    It can help you to have updated information in the application whenever something changes in the document. The voting system which I use is collecting 5 stars, 4 stars , 3 stars, etc, separately. For example: how many 5 stars ratings a user got, how many 4 stars a user got and so on. Then, to calculate the average rating I use the following formula:

    ((no_of_votes_for_5stars * 5) + (no_of_votes_for_4stars * 4) + (no_of_votes_for_3stars * 3) + (no_of_votes_for_2stars * 2) + (no_of_votes_for_1star * 1)) / (no_of_votes_for_5stars +no_of_votes_for_4stars + no_of_votes_for_3stars + no_of_votes_for_2stars + no_of_votes_for_1star )
    

    You can save the number of stars data separately in the Firestore database and whenever someone rates a photo, you can increment the current count. And you can implement the above formula inside the app code so your application gets the number of stars info and calculates the average using the above formula, and then displays it.