Home > Software design >  Flutter: How to Delete an Array Item in Multiple Documents of a Collection?
Flutter: How to Delete an Array Item in Multiple Documents of a Collection?

Time:08-04

I am working on deleting documents and removing items when a user deletes their account. In this case, I have a Firebase collection chats that holds an array users for all of the users within that chat. When someone deletes their account, I want that specific user to be removed from the users array. Here is how I am getting the docs:

var chatsUserIn = await instance.collection('chats').where('users', arrayContains: currentUserReference).get();

And that query is working fine. So if the user is in multiple chats (likely), then it will return multiple documents. However, what I cannot figure out how to do it go through each one of those docs and delete the user from the array users within the document. I do not want to delete the document completely, just remove the user from the array. I know I need to use some various of FieldValue.arrayRemove() but I cannot figure out how to remove the user from each individual document. Thanks for your help!

Update: I tried the following, but it did not delete the user from the array.

chatsUserIn.docs.forEach((element) => FieldValue.arrayRemove([currentUserReference]));

CodePudding user response:

You want to update these documents, so at the top level it's an update call:

chatsUserIn.docs.forEach((doc) {
  doc.reference.update({ 
    'users': FieldValue.arrayRemove([currentUserReference]) 
  });
});

CodePudding user response:

You actually want to update a group of Firestore documents. Cloud Firestore does not support the write queries to group documents, this in contrast to read queries witch are also possible on a group of documents.

You must have the doc ID to create a reference to it, and then make an Update request.

db.collection("chats").where("users", arrayContains
: userReference).get().then(
      (res) => res.mapIndexed(doc => doc.id))
      one rror: (e) => print("Error completing: $e"),
    );

then, you can send an Update query for each doc of the ID's results:

resultIDs.mapIndexed(id => {
final docReference = db.collection("chats").doc(id);
            docReference.update({
               "users": FieldValue.arrayRemove([currentUserReference]),
});
})
  • Related