繁体   English   中英

如何更新 Firestore 中的嵌套数组?

[英]How can I update nested array in Firestore?

我现在的数据库

有没有办法用 firebase firestore 更新点赞和回复?

当我对一条评论点赞时,我已经到了那一刻,但我只有对整个帖子的文档的引用,所以我没有对评论本身的引用。 我还使用 arrays 的查找方法找到了评论,但它不是评论本身的参考。

在此先感谢,我想我只需要重新考虑如何使用 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
    })
  }
}
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,
})

}

这就是我在同事的帮助下解决这个问题的方法。 基本上我是直接操作 likes 数组,然后更新整个帖子信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM