skip to Main Content

I have a collection in firebase called "community" and "users". All user records have a field "joinedCommunity" (a list of all joined communities).

I’m trying to figure a code that when a community is deleted, all user records are updated to only remove the community reference from "joinedCommunity" field list.

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 userRecordUpdate(DocumentReference community) async {
  final instance = FirebaseFirestore.instance;
  final batch = instance.batch();
  var collection = instance.collection('users');
  batch.update(collection, {
    "joinedCommunity": FieldValue.arrayRemove([community])
  });
  await batch.commit();
}

2

Answers


  1. Chosen as BEST ANSWER

    the following code worked -

    Future userRecordUpdate(DocumentReference community) async {
      final instance = FirebaseFirestore.instance;
      final batch = instance.batch();
      var collection = instance.collection('users');
      var snapshots =
          await collection.where("joinedCommunity", arrayContains: 
    community).get();
      for (var doc in snapshots.docs) {
        batch.update(doc.reference, {
          "joinedCommunity": FieldValue.arrayRemove([community])
        });
      }
      await batch.commit();
    }
    

  2. You’re using a CollectionReference, when what you want is a DocumentReference. As per the documentation, WriteBatch.update only works on a DocumentReference.

    I have a few suggestions:

    1. Try updating the field without using a WriteBatch. Use a for loop and a regular DocumentReference.update() call.
    2. Then, update your code to use a WriteBatch to update the field. Also, keep in mind a batch is limited to 500 operations.
    3. Finally, consider the security implications of allowing a client to be able to update any User document. You should probably update your security rules so that a user document can only be modified by that user. This code is probably something that should run in a Firebase Cloud Function that gets triggered whenever a community document is deleted.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search