Home > database >  How to find Firebase document field and delete document
How to find Firebase document field and delete document

Time:11-23

I have a button that lets a user delete their account. When users signup their email and name is saved to a Firestore collection called users, I want to search in the collection's documents where the uid field is equal to the current user uid then delete that document. Deleting the account works but not the document and I'm not getting any errors, I'm not sure what I'm doing wrong...

CollectionReference users = FirebaseFirestore.instance.collection('users');

TextButton(
         onPressed: () async { 
             try {
               await users
                     .where('uid', isEqualTo: _auth.currentUser!.uid).firestore.doc(users.doc().path).delete();
               await _auth.currentUser!.delete().then((value) => 
                Navigator.pushReplacement(context, MaterialPageRoute(
                      builder: (context) => const WelcomeScreen())));
                      } on FirebaseAuthException catch (error) {
                        Fluttertoast.showToast( msg: error.message.toString(),
                        gravity: ToastGravity.TOP,
                        backgroundColor: Colors.red,
                        textColor: Colors.white);
                        } on FirebaseException catch (error) { Fluttertoast.showToast(
                        msg: error.message.toString(),
                        gravity: ToastGravity.TOP,
                        backgroundColor: Colors.red,
                        textColor: Colors.white);
                       }
                 },
                      child: const Text( 'Delete', style: TextStyle(color: Colors.red),
  ))

CodePudding user response:

I got the problem I was just working on my app and found a similar code so here is the solution. Just declare user id as variable for ease not necessary (optional) like this

final uid = _auth.currentUser!.uid; //optional

& then use this in your code:-

await users.doc(uid).delete();

instead of

await users
           .where('uid', isEqualTo: _auth.currentUser!.uid).firestore.doc(users.doc().path).delete();

and Boom now it works like an charm!! Hope this works!!

  • Related