简体   繁体   English

将 object 添加到数组 Google Firestore

[英]Add object to array Google Firestore

Does somebody know how to add an object to an array in Google Firestore?有人知道如何将 object 添加到 Google Firestore 中的数组吗? I've searched everywhere and tried a lot of things but nothing worked out.我到处搜索并尝试了很多东西,但没有成功。 As you can see in the picture I'm using正如你在我使用的图片中看到的

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)
  });
};

But this only works for adding a basic value to the array.但这仅适用于向数组添加基本值。 If I want to add an object this doesn't works and I can't find any solution online.如果我想添加一个 object,这是行不通的,我在网上找不到任何解决方案。

I'm using javascript/web.我正在使用 javascript/web。

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

Your code should work.您的代码应该可以工作。 Note that you don't need to do await db.collection("livestreams").doc(docID);请注意,您不需要执行await db.collection("livestreams").doc(docID); since doc() is not asynchronous.因为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 ...        
    }

};

However, note four important points:但是,请注意四个要点:

  1. The update() method works only if the document already exists. update()方法仅在文档已经存在时才起作用。 You may use set() with the merge option if your know your doc might not exist.如果您知道您的文档可能不存在,您可以将set()合并选项一起使用。
  2. If you call twice the arrayUnion() method with the exact same object, no new array element is created.如果您使用完全相同的 object 调用两次arrayUnion()方法,则不会创建新的数组元素。
  3. Double check that your security rules allow the update.仔细检查您的安全规则是否允许更新。
  4. Add a try/catch to check if you get an error.添加 try/catch 以检查是否出现错误。

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

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