简体   繁体   中英

Add object to array Google Firestore

Does somebody know how to add an object to an array in 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.

I'm using javascript/web.

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

Your code should work. Note that you don't need to do await db.collection("livestreams").doc(docID); since doc() is not asynchronous.

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. You may use set() with the merge option if your know your doc might not exist.
  2. If you call twice the arrayUnion() method with the exact same object, no new array element is created.
  3. Double check that your security rules allow the update.
  4. Add a try/catch to check if you get an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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