How can I delete a document with all its subcollections in firebase with flutter and dart

161

Deleting a document does not automatically delete all documents in its sub-collections.

There is no method in firestore API to delete subcollections along with the document. You need to loop through and delete the documents in subcollections and then delete the parent document.

Here's a link for better understanding.

Share:
161
Gkon
Author by

Gkon

Updated on January 02, 2023

Comments

  • Gkon
    Gkon over 1 year

    Every time I try to delete a document programmatically using documentSnapshot.delete(), the firebase only deletes the document and not its subcollections. I want to permanently delete a document and all its subcollections with the push of a button and every time the user tries to create the same document, it'd be empty.

    What's the proper way to do that?

    (CLOSED)

    This is the code that worked for me:

    CollectionReference<Map<String, dynamic>> collectionReference = FirebaseFirestore.instance.collection('collection name').doc('document name').collection('collection name');
    DocumentReference<Map<String, dynamic>> documentReference = collectionReference.doc('document name');
    
    documentReference.collection('lists').get().then((lists) {
        lists.docs.forEach((listElement) {
          documentReference.collection('lists').doc(listElement.id.toString()).collection('cards').get().then((cards) {
            cards.docs.forEach((cardElement) {
              documentReference.collection('lists').doc(listElement.id.toString()).collection('cards').doc(cardElement.id.toString()).delete();
            });
          });
          documentReference.collection('lists').doc(listElement.id.toString()).delete();
        });
      });
    
    await documentReference.delete();
    
    • bharats
      bharats over 2 years
      What is the code that you are using?
    • Gkon
      Gkon over 2 years
      @bharats I set a collectionReference variable to be equal to collectionReference = FirebaseFirestore.instance.collection('boards').doc(Firebase‌​Auth.instance.curren‌​tUser.uid).collectio‌​n('boards'); then I set a documentReference to be equal to DocumentReference<Map<String, dynamic>> documentReference = collectionReference.doc(thisSpecificBoardName); Then I have the command documentReference.delete()
    • Peter Koltai
      Peter Koltai over 2 years
      If using a cloud function for that is an option for you, check this out.