Firestore:删除多个文档尝试再次删除同一文档

时间:2020-07-26 20:28:58

标签: angular google-cloud-firestore angularfire

我正在基于文档中的属性设置一个删除多个Firestore文档的功能。它确实可以工作,但是执行时可能会尝试两次删除同一文档(添加了控制台日志语句以进行验证)。方法如下:

   async deleteDocuments<T>(collectionName: string, fieldToCheck: string, stringValueToCheck: string) {
      // Get a collection based on the field being checked and then set a property for document ID to 'id'
      this._afs.collection(collectionName)
         .ref.where(fieldToCheck, '==', stringValueToCheck)
         .onSnapshot(async x => {
            if (x) {
               x.forEach(async doc => {
                  try {
                     console.log(`deleting: ${collectionName}/${doc.id}`)
                     await doc.ref.delete();
                  } catch (error) {
                     console.log(error)
                  }
               })
            }
         })
   }

它不会在所有文档上重复尝试,这确实令人困惑。例如,我有三个文档,当我运行它时,它对两个文档进行了两次遍历,一次遍历了一个文档。我在另一套大约有十几个文档的文档上进行了尝试,结果似乎相同(尽管我对1:3的比例并不满意)。

1 个答案:

答案 0 :(得分:1)

您正在预订某个查询,并且当您删除一个或多个元素时,结果当然会改变。我已修复您的代码,因此您无需删除订阅即可删除它们一次。

async deleteDocuments<T>(collectionName: string, fieldToCheck: string, stringValueToCheck: string) {document ID to 'id'
      const docs = await this._afs.collection(collectionName)
         .ref.where(fieldToCheck, '==', stringValueToCheck)
         .get();
      docs.forEach(doc => doc.ref.delete());
   }