Mohammad Abd-Elmoniem
Mohammad Abd-Elmoniem

Reputation: 666

How to check if data matches field in array in flutter


I have a Firebase Firestore configuration as show below:

enter image description here

How would I check if eventParticipants's contains a uid matching the current user's uid? The below code used to work when eventParticipants used to be an array of user id's, but since creating more detailed array objects, the code seems to not work:

data["eventParticipants"]
        .contains({
  "uid": FirebaseAuth
      .instance.currentUser!.uid
      .toString()
})

Usually the above code would return a bool, and I would use the result in a ternary operator to load a widget, however, I am unable to rework the logic with the new array structure. Subsequently, how would I remove an array object if it's uid field matches the current user's id?

FirebaseFirestore
    .instance
    .collection(
        "events")
    .doc(document.id)
    .set(
  {
    "eventParticipants":
        FieldValue
            .arrayRemove([
      {
        "uid": FirebaseAuth
            .instance
            .currentUser
            ?.uid
      }
    ])
  },
  SetOptions(
      merge: true),
);

Any pointers would be appreciated!

Upvotes: 0

Views: 264

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

The arrayRemove (and arrayUnion and arrayContains) operators expect you to pass the complete, exact contents of the item in the array. In your case it looks for an item in the array with a single field uid with the value you pass.

So unless you know the values of all properties of the array item that you want to remove, you'll have to:

  1. Read the document with the array in it.
  2. Manipulate the array in your application code.
  3. Write the entire array back to the database.

Also see:

Upvotes: 2

Related Questions