簡體   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