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.

4
  • 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 Commented Mar 24, 2023 at 3: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. Commented Mar 24, 2023 at 7: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 of the step that you got stuck at. Commented Mar 24, 2023 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. Commented Mar 24, 2023 at 17:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.