如何在 JS / React JS 中的 FireStore 中设置和附加对象数组

How to set and append an array of objects in FireStore in JS / React JS

// sending contracts to user
export async function sendContractToOtherUser(email: string | any, contract: string) {
  try {

    let user : any = "";
    // search the users collection with the email and get the user id

    // Create a reference to the users collection
    const usersRef =  collection(db, "users");
    // Create a query against the collection.
    onSnapshot(usersRef, async(snapShot) => {
  
      snapShot.docs.forEach(doc => {
        if(doc.data().email === email) {
         user = doc.data();
        }} 
      );  
      console.log("//////user Found", user, typeof user, user.userID);

      // An Array which Contains an object
      const userContractData : any = [{
        userID : user.userID,
        contract: contract
      }];
      // setting the array 
      const newPendingContractRef : any = doc(db,"pendingContract", user.userID );
       await setDoc(newPendingContractRef,
        {...userContractData}
        , {merge: true});
      // console.log("/////////contract", pendingContract);

    });

  } catch (error) {
      console.log("/////////errror in sendContractToOtherUser", error);
  }
}

我想将 userContractData 附加到 pendingContract 集合的文档 (user.uid) 中的数组。但是我的代码所做的是它只更新第 0 个索引处已经存在的数据。我如何构造我的 userContractData 以及我可以附加到数组

setDoc 方法

您确实将第一个数组项的值设置为文档。尝试使用 arrayUnion() 将元素推送到数组:

await setDoc(newPendingContractRef,
        { contract: arrayUnion(...userContractData) }
        , {merge: true});