Xwingoga06
Xwingoga06

Reputation: 101

How to query an array on a db firestore?

I don't think I'm very far from the answer, I tried to query an id inside an array on Firestore.

I wanna compare the id of the participants.

Also my DB in Firestore:

enter image description here

And also my function, for the moment my function return size =0 so they can't catch the query.

const deleteAbuse = (type) => {
    const participants = channel?.otherParticipants;
    if (!participants || participants.length != 1) {
      return;
    }
    const myID = currentUser.id;
    const otherUserID = participants[0].id;
    console.log('id user', otherUserID);
    channelDB
      .where('participants.id', '==', otherUserID)
      .get()
      .then((querySnapshot) => {
        console.log(querySnapshot.size);
        querySnapshot.forEach((doc) => {
          console.log(doc.ref);
          //doc.ref.delete();
        });
      });
  };

Upvotes: 1

Views: 498

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138814

There is no way you can query filter your "channels" collection to get documents based only on a single field of an object that exists inside the participants array. In other words, you cannot create that filtering based only on that ID. To be able to filter the data, you should pass to the where() function, the entire object, and not only some partial data. The object should contain values for all the fields. Only the ID is not enough.

And also my function, for the moment my function return size =0

That's the expected behavior since in your array there isn't any object that holds only a single field called id. All objects hold 7 fields, or even more than that, as I cannot see all fields in your screenshot.

I wrote an article called:

Where you can find in the first part, the simplest way to get a custom object from an array of custom objects.

Alternatively, you can create an array that can hold only the IDs of the participants, filter the documents and create another database call to get their corresponding data.

Upvotes: 1

Related Questions