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

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();
}

Leave a Reply