Raunak Patel
Raunak Patel

Reputation: 3

Remove referenced document from array Field list type in a document

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

Upvotes: 0

Views: 147

Answers (2)

Raunak Patel
Raunak Patel

Reputation: 3

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

Upvotes: 0

Noel
Noel

Reputation: 7410

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.

Upvotes: 0

Related Questions