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

后端 未结 1 2033
梦毁少年i
梦毁少年i 2021-01-15 15:30

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

1条回答
  •  臣服心动
    2021-01-15 15:49

    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().getFirestore()
        .collection('messages')
        .where('users.user1ID',isEqualTo: true)
        .where('users.user2ID',isEqualTo: true)
        .getDocuments();
    

    0 讨论(0)
提交回复
热议问题