0

In firestore, i have a collection called questions of documents with the following structure

{ category : "animals",
topics : [ {title :"habitats", votes: 1}, {title :"pets", votes: 5} ] }

I want to build a function that receives title as parameter, and increments votes by one, with no success.

I am trying things like :

const docRef = doc(db, "questions", id);

await updateDoc(docRef, {
        topics: {
          name: topicName,
          vote: increment(1),
        },
      });

//with arrayUnion

await updateDoc(docRef, {
        topics: arrayUnion{
          name: topicName,
          vote: increment(1),
        },
      });

But the only thing I do is updating the array replacing the two objects with just a new one, or adding a new object to the two existing ones.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Rher
  • 1
  • 2
  • There is no operator to update an item in an array, only to remove or add complete items. To update an item you will have to: 1. Read the entire array from the document, 2. Update the item in the array in your application code, 3. Write the entire array back to the database – Frank van Puffelen Mar 24 '23 at 03:36
  • ok, i understand. Thank you ver much. Could you give a hint about how that would look with that collection? I am a bit lost at the moment. – Rher Mar 24 '23 at 07:50
  • I gave a 3 step way to implement this. If you're stuck at a specific step in that process, the best way to get help is by posting a new question with a [minimal repro](http://stackoverflow.com/help/mcve) of the step that you got stuck at. – Frank van Puffelen Mar 24 '23 at 15:09
  • Those indications I am sure has to be very helpful for more experienced guys, but with total beginners ... Thanks Anyway. To know that what i was trying to do wasn't possible it was helpful. In the end , i had to first remove the element from the array with `arrayRemove()` and then add it again with `arrayUnion` , with the updated field. Using `batch.commit()` to perform both operations. – Rher Mar 24 '23 at 17:16

0 Answers0