1

In my Firebase structure I have a collection and some sub-collections within it. I would like when I delete the collection, also delete the subcollections. I'm trying to do what's in the Firebase documentation: "To delete an entire collection or subcollection in Cloud Firestore, retrieve all the documents within the collection or subcollection and delete them". But is not working. I delete the collection and the subcollection still saved. My code:

    void deleteNestedSubcollections(String id) {

    Future<QuerySnapshot> books = libraryCollection.document(id).collection("Books").getDocuments();
    books.then((value) => value.documents.remove(value));

    Future<QuerySnapshot> catalogues = libraryCollection.document(id).collection("Catalogues").getDocuments();
    catalogues.then((value) => value.documents.remove(value));
  }

EDIT 1

enter image description here

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Liam Park
  • 414
  • 1
  • 9
  • 26
  • You do not show your db structure so it is not obvious what are collections and what are subcollections. Please show your collection / subcollections structure. – GrahamD May 30 '20 at 15:58
  • Thanks for your answer. I edited my question and added the database structure – Liam Park May 30 '20 at 16:16
  • Have you checked this part of the documentation. It appears to recommend deleting subcollections via a called cloud function rather than from the app: https://firebase.google.com/docs/firestore/solutions/delete-collections – GrahamD May 30 '20 at 16:37
  • Yes, I read. Said that cloud function is better when there are more than 500 documents to delete. At this moment is not my case, maybe in future – Liam Park May 30 '20 at 17:10

1 Answers1

5

To delete a document, you need to use the delete method:


  void deleteNestedSubcollections(String id) {
    Future<QuerySnapshot> books =
        libraryCollection.document(id).collection("Books").getDocuments();
    books.then((value) {
      value.documents.forEach((element) {
        libraryCollection
            .document(id)
            .collection("Books")
            .document(element.documentID)
            .delete()
            .then((value) => print("success"));
      });
    });
  }
Peter Haddad
  • 78,874
  • 25
  • 140
  • 134