Geogram
Geogram

Reputation: 140

How to delete a Subcollection in Firestore using AngularFire2?

How do I delete a Subcollection using AngularFire2? I have the following in my component.ts file with the dependencies. the id in updateUser() is passed by client side action. I'm not receiving any errors in console, but firestore isn't deleting the data either:

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)
        });
    )
}

Upvotes: 1

Views: 1056

Answers (1)

Santosh Kadam
Santosh Kadam

Reputation: 1352

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.

Upvotes: 1

Related Questions