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
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
how to solve this error ?
2
Answers
According to Delete documents Firebase Docs
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
it seems that there are two issues that you need to address.
removing the user document does not automatically remove its
subcollections. Therefore, you need to iterate through each
subcollection’s documents to delete them.
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: