Home > Net >  How do I delete all Firestore documents for a specific user, based on a substring of the document ID
How do I delete all Firestore documents for a specific user, based on a substring of the document ID

Time:05-30

How do I delete all Firestore documents for a specific user? The Document IDs all begin with the user ID but include further unique identifiers after that (which is why I'm using a substring). Below is the code:

ElevatedButton(
      onPressed: () async {
        setState(() {
          final userIdForDelete = FirebaseAuth.instance.currentUser?.uid;
          final userDocsForDelete = FirebaseFirestore.instance
              .collection('user_docs')
              .doc(userIdForDelete?.substring(0, 28));
          if (userDocsForDelete != null) {
            userDocsForDelete.delete().then(
                  (doc) => debugPrint(
                  "User Documents Deleted"),
              one rror: (e) => debugPrint(
                  "User Documents NOT Deleted $e"),
            );
          }
        });
      },
      child: const Text('Delete My Docs'),
    );

CodePudding user response:

If the document IDs all start with the value you want to select on, you can use a condition on the name like this:

var prefix = userIdForDelete?.substring(0, 28);

final userDocsForDelete = FirebaseFirestore.instance
    .collection('user_docs')
    .where(FieldPath.documentId, isGreaterThanOrEqualTo: prefix)
    .where(FieldPath.documentId, isLessThan: prefix   "~");

This only works for so-called prefix searches though, not for searches IDs that contain or end with a specific value. If you need those, consider storing the value you want to search for as a field in the document, so that you can put the condition on that field.

Also see:

CodePudding user response:

I landed up adding a field in the document with the uid and used the batch delete method. This code seems to works.

ElevatedButton(
  onPressed: () async {
    setState(() async {

      final userIdForDelete = FirebaseAuth.instance.currentUser?.uid;

      WriteBatch batch = FirebaseFirestore.instance.batch();

      await FirebaseFirestore.instance
          .collection('user_document')
          .where('00_UID', isEqualTo: userIdForDelete)
          .get()
          .then((querySnapshot)=>{
        querySnapshot.docs.forEach((document) {
          batch.delete(document.reference);
        })
      });
      batch.commit().then((document) {
        debugPrint('User Documents Deleted');
      });
      
    });
  },
  child: const Text('Delete User Data'),
);
  • Related