skip to Main Content

I tried to delete firebase collection document and with that delete all the sub collections and remove from authentications also using flutter. here it is my database screenshot

enter image description here

I want delete user document with those subcollection (books and pdfs).

my code

  void deleteUserDocument() async {
    final sp = context.watch<SignInProvider>();
    try {
      // Get the current user's ID
      final user = FirebaseAuth.instance.currentUser;
      final uid = user?.uid;
      if (uid != null) {
        // Get a reference to the user's document in Firestore
        final docRef = FirebaseFirestore.instance.collection("users").doc(uid);
        // Delete all subcollections in the user's document
        final collections = await FirebaseFirestore.instance.collection("users").doc(uid).listCollections();
        final batch = FirebaseFirestore.instance.batch();
        for (final collectionRef in collections) {
          final querySnapshot = await collectionRef.get();
          for (final docSnapshot in querySnapshot.docs) {
            batch.delete(docSnapshot.reference);
          }
          batch.delete(collectionRef);
        }
        await batch.commit();
        // Delete the user's document
        await docRef.delete();
        // Remove the user from Firebase Authentication
        await user?.delete();
        // Log the user out and navigate to the login screen
        sp.userSignOut();
        nextScreenReplace(context, const LoginScreen());
      }
    } catch (e) {
      // Handle any errors that occur during the deletion process
      print('Error deleting user document: $e');
      // Display an error message to the user
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to delete account')),
      );
    }
  }

but in there show error on ** final collections = await FirebaseFirestore.instance.collection("users").doc(uid).listCollections();**

error screenshot

enter image description here

how to solve this error ?

2

Answers


  1. According to Delete documents Firebase Docs

    Warning: Deleting a document does not delete its subcollections!

    And

    Deleting collections from the client is not recommended.

    Instead you should delete the document which have subcollections with Delete data with a Callable Cloud Function and call it from your client Application.

    Firebase Docs has also provided a sample firebase function to delete the document which you can check here : Solution: Delete data with a callable Cloud Function

    Login or Signup to reply.
  2. it seems that there are two issues that you need to address.

    • The first one, as pointed out by Rohit Kharche earlier, is that
      removing the user document does not automatically remove its
      subcollections. Therefore, you need to iterate through each
      subcollection’s documents to delete them.
    • The second issue is related
      to Firebase batch, which has a limit of 500 documents. In case the
      subcollection has more than 500 documents, the batch operation will
      fail and the deletion process won’t be completed.

    The below code solution addresses all these issues:

    void deleteUser() async {
      final sp = context.watch<SignInProvider>();
    
      /* Since we are using batch to delete the documents usually the max batch size
      * is 500 documents.
      */
      const int maxBatchSize = 500;
    
      // Define the users collections;
      final List<String> collections = [
        "books",
        "pdfs",
      ];
    
      try {
        // Get the current user's ID
        final String? uid = FirebaseAuth.instance.currentUser?.uid;
    
        //loop through collection and delete each collection item from a user
        for (String collection in collections) {
          // Get the snapshot of a collection.
          final QuerySnapshot snapshot = await FirebaseFirestore.instance
              .collection('Users')
              .doc(uid)
              .collection(collection)
              .get();
          // Get the list of documents;
          final List<DocumentSnapshot> querySnapshotList = snapshot.docs;
    
          // Get the length of the list(no of documents in the collections)
          final int documentLengths = querySnapshotList.length;
    
          /* The below code allows us too loop through the documents and delete
          them after every 500 documents, since batch is full at 500.
           */
          final int loopLength = (documentLengths / maxBatchSize).ceil();
          for (int _ = 0; _ < loopLength; _++) {
            final int endRange = (querySnapshotList.length >= maxBatchSize)
                ? maxBatchSize
                : querySnapshotList.length;
            // Define the batch instance
            final WriteBatch batch = FirebaseFirestore.instance.batch();
            for (DocumentSnapshot doc in querySnapshotList.getRange(0, endRange)) {
              batch.delete(doc.reference);
            }
            // Commit the delete batch
            batch.commit();
            querySnapshotList.removeRange(0, endRange);
          }
        }
        // Delete the user profile
        await FirebaseFirestore.instance.collection('Users').doc(uid).delete();
    
        // Log out user from all platforms.
        sp.userSignOut();
        /*
        // Log out user from all platforms.
        Future.wait([
          _googleSignIn.signOut(),
          _facebookAuth.logOut(),
          _firebaseAuth.signOut(),
        ]);
         */
      } catch (e) {
        // Handle any errors that occur during the deletion process
        print('Error deleting user document: $e');
        // Display an error message to the user
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to delete account')),
        );
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search