1

I have created a comment section in my react app. The comment section has following data structure in the firestore:-

    comments: [{
        comment: "First comment",
        replies: [{
            reply: "first reply"
        }]
    },{
        comment: "Second comment",
        replies: [{
            reply: "first reply"
        }]
    }]

If I want to add a new comment I do this by: -

db.collection("myCollection").doc("0").update({
    comments: firebase.firestore.FieldValue.arrayUnion({
        comment: "New Comment",
        replies: []
    })
})

Now, what I actually want to do is to do is to add a new reply to the existing comment. But I can't find any way to do it. For example, I want this to happen in the data structure defined above: -

    comments: [{
        comment: "First comment",
        replies: [{
            reply: "first reply"
        },{
            reply: "second reply"
        }]
    },{
        comment: "Second comment",
        replies: [{
            reply: "first reply"
        }]
    }]

So how can I do this?

Please help me solve this. Thank you!

Zaeem Khaliq
  • 296
  • 5
  • 14

1 Answers1

1

You're trying to update an array element by its index, which is not an atomic operation on Firestore.

You'll need to:

  1. Read the document and retrieve the comments array from it.
  2. Update the comments array in your application code.
  3. Write the updated comments array back to the document.

If you were to store the comments in a subcollection, you can probably use an arrayUnion to update a specific comment, since then the replies are a top-level field in that document. But I doubt it is worth the added overhead of the additional documents and document read operations in this scenario.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Yes this is exactly what I am actually doing. Reading the whole array of objects then sending back after modifying. Was just wondering if there was an easy way to do this. Anyways, Thank you! – Zaeem Khaliq May 17 '21 at 15:26