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!

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.