【问题标题】:How to delete a Subcollection in Firestore using AngularFire2?如何使用 AngularFire2 删除 Firestore 中的子集合?
【发布时间】:2018-04-05 04:01:43
【问题描述】:

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

【问题讨论】:

    标签: angular firebase google-cloud-firestore angularfire2


    【解决方案1】:

    根据官方文档,不建议从客户端代码中删除集合。我们可以在集合中一个一个地删除文档,但不能一次删除整个集合。 这似乎也是合乎逻辑的,因为删除文档类似于从我们的传统数据库中删除表。如果我们通过循环遍历所有文档来删除集合中的所有文档,则集合将被自动删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2018-07-20
      • 1970-01-01
      相关资源
      最近更新 更多