Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Delete all documents in collection in Firestore with Flutter

Tags:

I have a firestore database. My project plugins:

cloud_firestore: ^0.7.4 firebase_storage: ^1.0.1

This have a collection "messages" with a multiple documents. I need to delete all documents in the messages collection. But this code fail:

Firestore.instance.collection('messages').delete();

but delete is not define

how is the correct syntax?

like image 546
ALEXANDER LOZANO Avatar asked Oct 31 '18 18:10

ALEXANDER LOZANO


People also ask

How do you delete a file from firestore using where clause?

To delete document from Firestore using where clause with JavaScript, we can use the delete method. const jobSkills = await store . collection("job_skills") . where("job_id", "==", post.


2 Answers

Ah. The first answer is almost correct. The issue has to do with the map method in dart and how it works with Futures. Anyway, try using a for loop instead like so and you should be good:

firestore.collection('messages').getDocuments().then((snapshot) {
  for (DocumentSnapshot ds in snapshot.documents){
    ds.reference.delete();
  });
});
like image 107
Ryan Newell Avatar answered Sep 24 '22 22:09

Ryan Newell


As stated in Firestore docs, there isn't currently an operation that atomically deletes a collection.

You'll need to get all the documents, and loop through them to delete each of them.

firestore.collection('messages').getDocuments().then((snapshot) {
  for (DocumentSnapshot doc in snapshot.documents) {
    doc.reference.delete();
  });
});

Note that this will only remove the messages collection. If there are subcollections in this path they will remain in Firestore. The docs also has a cloud function also integration with a Callable function that uses the Firebase Command Line Interface to help with dealing nested deletion.

like image 38
Joshua Chan Avatar answered Sep 23 '22 22:09

Joshua Chan