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

时间:2018-04-05 04:01:43

标签: angular firebase google-cloud-firestore angularfire2

如何使用AngularFire2删除子集合?我在带有依赖项的component.ts文件中有以下内容。 id中的updateUser()由客户端操作传递。我没有在控制台中收到任何错误,但是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)
        });
    )
}

1 个答案:

答案 0 :(得分:1)

根据官方文档,不建议从客户端代码中删除集合。我们可以一次删除一个集合中的文档,但不能一次删除整个集合。 这似乎也合乎逻辑,因为删除文档与从传统数据库中删除表格相似。如果我们通过逐个循环浏览集合中的所有文档来删除集合中的所有文档,则会自动删除。