How to access array index of Cloud Firestore using query in Flutter?

161
January 27, 2021, at 08:50 AM

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

Answer 1

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();
READ ALSO
Getting an unwanted space between Nav Items in Navbar Angular

Getting an unwanted space between Nav Items in Navbar Angular

I am trying to create a sidenav bar with nav items in it which has sub menusI am able to create it but i am getting space between 2 navitems which have submenus

52
PHP Script INSERT INTO SELECT does not insert, with no errors [closed]

PHP Script INSERT INTO SELECT does not insert, with no errors [closed]

Want to improve this question? Update the question so it's on-topic for Stack Overflow

92
SQL query to select students who have taken all subjects from subjects table

SQL query to select students who have taken all subjects from subjects table

I have two tables, student_records and subjectsI have to find out those students who have taken all the subjects (1,2,3) from the subjects table

90
Sticky view with scrollview and expandable background

Sticky view with scrollview and expandable background

How can we make a view in red border sticky which does not depend on the height of black background and always stick with a border of black and white background

127