3

I have field users in document and this field contains two element in array. I have to check specific two values are in this array.

First, I used array-contains method twice for this, but it occurred error.

How can I access index of array field in Cloud Firestore?

Below code is my approach and it is not working:

QuerySnapshot querySnapshot = await sl.get<FirebaseAPI>().getFirestore()
      .collection('messages')
      .where('users'[0],isEqualTo: 'user1ID')
      .where('users'[1],isEqualTo: 'user2ID')
      .getDocuments();

simple firestore structure

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Privacy of Animal
  • 441
  • 2
  • 10
  • 17

1 Answers1

10

There is no way Firestore in which you can query the database based on an index of an element that exist within an array. It's true that you cannot chain more than one array-contains calls in a query but there is another workaround that can help you achieve the same thing. So a change is needed in your database structure. So instead of using an array you can use a map and your schema should look similar to this:

Firestore-root
   |
   --- messages (collection)
         |
         --- users (map)
              |
              --- user1ID: true
              |
              --- user2ID: true

Now a query like this will work perfectly fine:

QuerySnapshot querySnapshot = await sl.get<FirebaseAPI>().getFirestore()
    .collection('messages')
    .where('users.user1ID',isEqualTo: true)
    .where('users.user2ID',isEqualTo: true)
    .getDocuments();
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193