Firebase 如何在firestore中删除多个具有特定值的文档
我试图从我的收藏中删除许多具有特定categoryId值的文档,但我认为这样做是错误的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
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();
}
有两个问题:
forEach
(对于每个文档,而不是对于具有特定类别ID的文档),但应该只触发一次,或者可能有更好更简单的方法根据特定条件删除所有文档#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());
}