Usman Ahmed Naushahi
Usman Ahmed Naushahi

Reputation: 229

FLUTTER: How to delete multiple documents using where clause in cloud firestore?

I want to delete the documents where the driverID is equivelant to the logged-in user ID. I am using the code below, and its not working.

      requestToJoinReference.where('driverID'==user.uid).getDocuments().then((snapshot) {
        for(DocumentSnapshot ds in snapshot.documents)
          {
            // ds.reference.delete();
            print(ds.reference);
          }
      });

Upvotes: 5

Views: 2371

Answers (1)

sameer kashyap
sameer kashyap

Reputation: 1166

This is not the right syntax to use the where clause in firebase, what you are looking for is

 requestToJoinReference.where('driverID', isEqualTo: user.uid).getDocuments().then((snapshot) {
        for(DocumentSnapshot ds in snapshot.documents)
          {
            //ds.reference.delete();
            print(ds.reference);
          }
      });

Also, delete() is aysnc so you would have to make your forEach loop async as well

requestToJoinReference.where('driverID', isEqualTo: user.uid).getDocuments().then((snapshot) {
        for(DocumentSnapshot ds in snapshot.documents)async {
            await ds.reference.delete();
            print(ds.reference);
          }
      });

And, this is not the recommended way to perform multiple deletes, what you need is Batch write, Batch writes allows you to execute multiple write operations as a single batch that can contain any combination of set, update, or delete operations.

Future<void> batchDelete() {
  WriteBatch batch = FirebaseFirestore.instance.batch();

  return  requestToJoinReference.where('driverID', isEqualTo: user.uid).get().then((querySnapshot) {

    querySnapshot.documents.forEach((document) {
      batch.delete(document.reference);
    });

    return batch.commit();
  });
}

I would also recommend you to upgrade your dependencies to the lastest version and refer the FlutterFire documentation for syntax changes.

Upvotes: 7

Related Questions