简体   繁体   English

如何使用AngularFire2在Firestore中删除子集合?

[英]How to delete a Subcollection in Firestore using AngularFire2?

How do I delete a Subcollection using AngularFire2? 如何使用AngularFire2删除子集合? I have the following in my component.ts file with the dependencies. 我的component.ts文件中包含以下内容: the id in updateUser() is passed by client side action. 客户端操作传递updateUser()id I'm not receiving any errors in console, but firestore isn't deleting the data either: 我没有在控制台中收到任何错误,但是firestore也没有删除数据:

 import { Component, OnInit} from '@angular/core'; import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection } from 'angularfire2/firestore'; import { Observable } from 'rxjs/Observable'; import { fromPromise } from 'rxjs/observable/fromPromise'; import { expand, takeWhile, mergeMap, take } from 'rxjs/operators'; constructor(private afs: AngularFirestore) {} //... @Component, export class, etc. updateUser(role, id){ if(window.confirm('Are you sure?')){ const path = `users/${id}/roles`; this.deleteCollection(path, 25); // do other things... } } deleteCollection(path: string, batchSize: number): Observable<any> { const source = this.deleteBatch(path, batchSize) // expand will call deleteBatch recursively until the collection is deleted return source.pipe( expand(val => this.deleteBatch(path, batchSize)), takeWhile(val => val > 0) ) } // Deletes documents as batched transaction private deleteBatch(path: string, batchSize: number): Observable<any> { const colRef = this.afs.collection(path, ref => ref.orderBy('__name__').limit(batchSize) ) return colRef.snapshotChanges().pipe( take(1), mergeMap(snapshot => { // Delete documents in a batch const batch = this.afs.firestore.batch(); snapshot.forEach(doc => { batch.delete(doc.payload.doc.ref); }); return fromPromise( batch.commit() ).map(() => snapshot.length) }); ) } 

As per official documentation deleting collection from client code is not recommended. 根据官方文档,不建议从客户端代码中删除集合。 We can delete document one by one within collection but not whole collection at once. 我们可以一次删除一个集合中的文档,但不能一次删除整个集合。 It also seems logical because deleting document would be similar to deleting table from our traditional databases. 这似乎也合乎逻辑,因为删除文档与从传统数据库中删除表格相似。 If we delete all documents within collection by looping over all it's documents one by one collection will get deleted automatically. 如果我们通过逐个循环浏览集合中的所有文档来删除集合中的所有文档,则会自动删除该集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM