javascript 更新firebase文档中的单个值

mbzjlibv  于 5个月前  发布在  Java
关注(0)|答案(2)|浏览(57)

第一次使用firebase,我正在创建一个博客,当我创建一个帖子时,我正在创建它:

const postCollection = collection(database, "posts");

  const submitPost = async () => {
    await addDoc(postCollection, {
      title,
      body,
      comments: [],
      liked: false,
      user: { name: auth.currentUser.displayName, id: auth.currentUser.uid },
    });
  };

字符串
在每一篇文章下面我都有一个评论部分,但是我对添加评论有点困惑。
我试过这个:

const addComment = async (id) => {
    const targetPost = doc(database, "posts", id);
    await setDoc(targetPost, { ...targetPost, comments: [comment] });
  };


但没成功。先谢谢你了

dy2hfwbg

dy2hfwbg1#

如果一篇文章已经存在,那么你可以使用updateDoc()来更新该文档中的特定字段,而不是setDoc(),如果存在,setDoc()将覆盖文档。由于'comments'是一个数组,你可以使用arrayUnion()来推送新的评论到你的文章中,如下所示:

import { doc, updateDoc, arrayUnion } from "firebase/firestore";

const addComment = async (id) => {
  const targetPost = doc(database, "posts", id);

  await updateDoc(targetPost, {
    comments: arrayUnion(comment)
  });
};

字符串
不要这样,如果你需要更新一个特定的评论,那么你必须阅读整个帖子文档,手动更新评论数组,然后写回整个评论数组:

import { doc, getDoc, updateDoc } from "firebase/firestore";

const addComment = async (id) => {
  const targetPost = doc(database, "posts", id);
  
  const snapshot = await getDoc(targetPost)

  await updateDoc(targetPost, {
    comments: [...snapshot.data().comments, comment]
  });
};


还 checkout :Is there any way to update a specific index from the array in Firestore
如果你知道comment对象,你可以使用arrayRemove()来删除一个特定的注解。

qf9go6mv

qf9go6mv2#

在React js中更新Firebase Firestore中的文档
--import line-- import { collection,doc,getDoc,setDoc,updateDoc } from 'firebase/firestore'

await updateDoc(doc(db, "Requests", id), {
  fieldName: newValue //field which you have to update
})

字符串
这很简单

相关问题