Firebase 如何在firestore中删除多个具有特定值的文档

Firebase 如何在firestore中删除多个具有特定值的文档,firebase,google-cloud-firestore,angularfire2,Firebase,Google Cloud Firestore,Angularfire2,我试图从我的收藏中删除许多具有特定categoryId值的文档,但我认为这样做是错误的 async deleteCol(id: string) { const cars: firebase.firestore.QuerySnapshot = await this.db.collection('cars', ref => ref.where('categoryId', '==', id)).ref.get(); const batch = this.db.fir

我试图从我的收藏中删除许多具有特定categoryId值的文档,但我认为这样做是错误的

async deleteCol(id: string) {
    const cars: firebase.firestore.QuerySnapshot 
      = await this.db.collection('cars', ref => ref.where('categoryId', '==', id)).ref.get();
    const batch = this.db.firestore.batch();

    cars.forEach(car => {
      batch.delete(car);
    });

    batch.commit();
  }
有两个问题:

  • typescript显示批处理中car的错误。删除(car)

    “QueryDocumentSnapshot”类型的参数不能分配给“DocumentReference”类型的参数。类型“QueryDocumentSnapshot”中缺少属性“firestore”

  • 例如,如果有两辆车,并且每辆车都有不同的类别ID,则会触发两次
    forEach
    (对于每个文档,而不是对于具有特定类别ID的文档),但应该只触发一次,或者可能有更好更简单的方法根据特定条件删除所有文档

  • 更新:

    好的,那么这个版本正在运行:)

    公共异步deleteCol(id:string):承诺{ const carsList:Observable=wait this.db.collection('cars',ref=>ref.where('categoryId','=',id)).get(); const batch=this.db.firestore.batch(); 汽车排气管( 合并地图(cars=>cars.docs), map((car:QueryDocumentSnapshot)=>batch.delete(car.ref)) ).toPromise()。然后(()=>batch.commit()); }
    #2之所以发生,是因为您使用
    .ref.get()
    结束查询。其中的
    .ref
    返回对整个集合的引用,实质上再次抛出您构建的查询。因此,删除
    .ref
    并简单地
    .get()
    查询结果。是的,你是对的。我更新了我的版本,所以现在它工作正常:)很高兴听到!我投票认为这是一个打字错误,因为其他犯同样错误的开发人员不太可能找到你的问题。这不仅仅是一个类型,所以我不能做你想做的。我在代码中添加了更多更改。
    public async deleteCol(id: string): Promise<void> {
        const carsList: Observable<firestore.QuerySnapshot> = await this.db.collection('cars', ref => ref.where('categoryId', '==', id)).get();
        const batch = this.db.firestore.batch();
        carsList.pipe(
          mergeMap(cars => cars.docs),
          map((car: QueryDocumentSnapshot) => batch.delete(car.ref))
        ).toPromise().then(() => batch.commit());
      }