如何在包含文档中对象的对象数组中搜索特定字段并在 firestore (firebase) (JS) 中更新它们

问题描述 投票:0回答:1

// Update the other user that current user has asked for revision
export async function updateOtherUserForContractRevision(contractID : string, comments : any) {
   // getting userDetails
   let currentUser : string | any = localStorage.getItem("userDetails");
   currentUser = JSON.parse(currentUser);

   // update fields in contractRecieved
   const contractsRecievedRef : any =  doc(db, "contractsRecieved", currentUser.uid);
   
  //  const queryContractsRecieved = query(contractsRecievedRef,
  //   where('contractDetails.contract.contractID','array-contains',contractID)    
  //   );
  // console.log(".////////updateOtherUserForContractRevision", queryContractsRecieved ,contractID)

  onSnapshot(contractsRecievedRef, (doc: any) => {
    doc.data().contract.map((contract: any) => {
      if(contract.contractDetails.contract.contractID === contractID) {
        // I reach my desired array Index and want to update the msg field to my comments parametre
        console.log(".////////contract", contract);
      }
    })
  })
    


}

我想更新我的

msg
字段以及
content
对象中的
contract
字段,而该字段又存在于
contractDetails
数组(第 0 个索引)中的
contract
对象中。我已经使用
onSnapShot
搜索并达到了我想要的数组值,如何在
onSnapShot
方法中更新这些字段?或者我应该使用另一种方法来搜索和更新数组包含的对象中的字段。

只是一个想法:如果我可以获得对数组索引的引用,然后用它来更新对象,也许它会起作用

例如(我会更新

sentForRevision

 onSnapshot(contractsRecievedRef, async (doc: any) => {
    doc.data().contract.map(async (contract: any) => {
      if(contract.contractDetails.contract.contractID === contractID) {
        console.log(".////////contract", doc.ref);
        // If this contract.ref exists and points to the index present in the document
        await updateDoc(contract.ref,{
          "contractDetails.sentForRevision": true,
        });
      }
    })
  })

javascript firebase google-cloud-platform google-cloud-firestore nosql
1个回答
4
投票

您无法根据数组中包含的对象中存在的值来查询 Firestore 集合。 使用部分数据无法实现这种过滤。我什至写了一篇关于这个主题的文章,名为:

如果需要,您可以复制要执行过滤的数据并将其添加到单独的数组中。这样,您就可以使用

array-contains
运算符查询集合。获得所需的文档后,您可以获取数组,执行更新,然后将文档写回 Firestore。

© www.soinside.com 2019 - 2024. All rights reserved.