Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deleting document(s) inside a collection with documentReference

I have a collection in firebase called "community" and "events".
When an event document is created, a field "communityRef" is included as docRef to community.

I’m trying to figure a code that when a community is deleted, all events related to the community are also deleted.

building this in flutterflow using custom action

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

onTap on a button in UI, the code is included as one of the actions before community document is deleted.

Future deleteAllRefEvents(DocumentReference community) async {
  final instance = FirebaseFirestore.instance;
  final batch = instance.batch();
  var collection = instance.collection('events');
  var snapshots = await collection.where('communityRef', isEqualTo: DocumentReference).get();
  for (var doc in snapshots.docs) {
    batch.delete(doc.reference);
  }
  await batch.commit();
}

>Solution :

You are passing DocumentReference type instead of variable community

Your code should be as following

Future deleteAllRefEvents(DocumentReference community) async {
  final instance = FirebaseFirestore.instance;
  final batch = instance.batch();
  var collection = instance.collection('events');
  var snapshots = await collection.where('communityRef', isEqualTo: community).get();//Here you used DocumentReference instead of community
  for (var doc in snapshots.docs) {
    batch.delete(doc.reference);
  }
  await batch.commit();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading