Skip to content
Advertisement

How to do arrayUnion on an array of objects inside another array of objects in firebase firestore?

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!

Advertisement

Answer

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:

Advertisement