繁体   English   中英

将 object 添加到数组 Google Firestore

[英]Add object to array Google Firestore

有人知道如何将 object 添加到 Google Firestore 中的数组吗? 我到处搜索并尝试了很多东西,但没有成功。 正如你在我使用的图片中看到的

const sendMessage = async (data, docID) => {
  const query = await db.collection("livestreams").doc(docID);
  const newDataObj = {
    created_At: data.created_At,
    displayName: data.displayName,
    message: data.message,
    ownerThumbnail: data.ownerThumbnail,
    userID: data.userID
  };
  const addObjToArr = await query.update({
    chat: firebase.firestore.FieldValue.arrayUnion(newDataObj)
  });
};

但这仅适用于向数组添加基本值。 如果我想添加一个 object,这是行不通的,我在网上找不到任何解决方案。

我正在使用 javascript/web。

将对象添加到 Google Firebase 中的数组

您的代码应该可以工作。 请注意,您不需要执行await db.collection("livestreams").doc(docID); 因为doc()不是异步的。

const sendMessage = async (data, docID) => {

   try {

      const query = db.collection("livestreams").doc(docID);  //<-- remove await
      const newDataObj = {
        created_At: data.created_At,
        displayName: data.displayName,
        message: data.message,
        ownerThumbnail: data.ownerThumbnail,
        userID: data.userID
      };
      const addObjToArr = await query.update({
        chat: firebase.firestore.FieldValue.arrayUnion(newDataObj)
      });

    } catch (error) {
       console.log(error);
       // return something ...        
    }

};

但是,请注意四个要点:

  1. update()方法仅在文档已经存在时才起作用。 如果您知道您的文档可能不存在,您可以将set()合并选项一起使用。
  2. 如果您使用完全相同的 object 调用两次arrayUnion()方法,则不会创建新的数组元素。
  3. 仔细检查您的安全规则是否允许更新。
  4. 添加 try/catch 以检查是否出现错误。

暂无
暂无

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

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