Adding rating to a movie using Firebase and React

I want to create a functionality where I add the people who added rating to a movie into an object called voters and from there I want to get the sum of those all of those ratings divided by the length of that object as a value of rating property, here is how my database looks like:

enter image description here

The issue I came across is that I can’t seem to add values or to be precise properties inside that voters object. I used updateDoc functionality from Firebase but anytime I log in with a different user and I rate the movie it overwrites the previous rating instead of adding a new property if you get what I am saying, here is my code:

export const rateMovie = (movieName, rating, uuid) => {
  updateDoc(doc(moviesCollectionRef, movieName), {
    voters: { [uuid]: rating },
  });
};

Does anyone know how to add new properties to an object inside Firebase collection without overwriting previous data?

>Solution :

As far as I can see your voters field is a map, in which case you can update the nested fields with dot notation:

const path = "voters." + uid;
updateDoc(doc(moviesCollectionRef, movieName), { 
  [path]: rating
});

Leave a Reply