1

I have a social media site where there are posts and there are comments and people can upvote or downvote posts and comments. Here is how a post looks like in form of an object on my firebase firestore database-

{
  author: 'Pranav',
  heading: 'randomHeading',
  content: 'randomContent',
  votes: 3,
  comments: [
    {
     id: 123,
     author: 'Pranav'
     content: 'commentContent',
     heading: 'commentHeading',
     votes: 2,
    },
    {
     id: 124,
     author: 'Pranav2'
     content: 'commentContent2',
     heading: 'commentHeading2',
     votes: 3,
    },
    {
     id: 125,
     author: 'Pranav3'
     content: 'commentContent3',
     heading: 'commentHeading3',
     votes: 4,
    }
  ]
}

Now I want to add functionality to update the votes of a particular comment but don't know how to access the comment with its ID, using the firebase firestore functions.


This is how I am getting the post doc in my code, just for reference if you can answer with the exact code for the query.

function voteComment(postId, vote){
  const docRef = doc(db, 'posts', postId);
  updateDoc(docRef, {<update-goes-here>})
}
Pranav_m7
  • 130
  • 2
  • 11
  • There isn't any direct way to update element at a specific index atm. You'll have to read the document and update the array back as explained in linked answers. If a post can have many comments (and the total size can exceed 1 MB that is max document size) then I'll recommend storing comments in a sub-collection. That way would be able to update comment by ID as well because each comment would be a document. – Dharmaraj Apr 10 '22 at 07:48
  • I think that this [article](https://medium.com/firebase-tips-tricks/how-to-update-an-array-of-objects-in-firestore-cdb611a56073), will help. – Alex Mamo Apr 10 '22 at 08:48

0 Answers0