'How can I update nested array in Firestore?
Is there a way to update the likes and replies with firebase firestore?
I have reached that moment when I press on like on a single comment but I have only the reference to the document of the whole post , so I don't have a reference to the comments itself. I also reached the comment with the find method of the arrays but it's not a reference its the comment itself.
Thanks in advance, I am thinking I just have to reconsider how i structure my DB using firestore?
const addLikeToComment = async (
postID: string,
commentID: string,
userID: string
): Promise<void> => {
const currentPost = await getPostById(postID)
const currentPostDocId = currentPost[0].docID!
const currentPostRef = doc(db, 'posts', currentPostDocId)
const commentToAddLikeTo = currentPost[0].comments.find(
(currComment) => currComment.commentID === commentID
)
console.log(commentToAddLikeTo)
if (!commentToAddLikeTo?.likes.includes(userID)) {
await updateDoc(currentPostRef, {
// add the like to comments - currentComment - likes array inside it push the userID
})
} else {
await updateDoc(currentPostRef, {
// remove the like
})
}
}
Solution 1:[1]
const addLikeToComment = async (
postID: string,
commentID: string,
userID: string
): Promise<void> => {
const currentPost = await getPostById(postID)
const currentPostDocId = currentPost[0].docID!
const currentPostRef = doc(db, 'posts', currentPostDocId)
const commentToAddLikeTo = currentPost[0].comments.find(
(currComment) => currComment.commentID === commentID
)
const newLikes = commentToAddLikeTo?.likes
if (!commentToAddLikeTo?.likes.includes(userID)) {
newLikes?.push(userID)
} else {
const indexOfUserID = newLikes?.indexOf(userID)
newLikes?.splice(indexOfUserID!, 1)
}
await updateDoc(currentPostRef, {
...currentPost[0],
likes: newLikes,
})
}
This is how I solved this with some help from a co-worker. Basically I am manipulating the likes array directly and then updating the whole post information.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

