如何使用 Flutter 中的查询访问 Cloud Firestore 的数组索引? [英] How to access array index of Cloud Firestore using query in Flutter?
问题描述
我在文档中有字段 users
并且该字段包含数组中的两个元素.我必须检查这个数组中的两个特定值.
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.
首先,我为此使用了两次 array-contains
方法,但出现错误.
First, I used array-contains
method twice for this, but it occurred error.
如何访问 Cloud Firestore 中数组字段的索引?
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();
推荐答案
Firestore 无法根据存在于数组中的元素的索引查询数据库.确实,您不能在查询中链接多个 array-contains
调用,但还有另一种解决方法可以帮助您实现相同的目标.所以你的数据库结构需要改变.因此,您可以使用地图而不是使用数组,并且您的架构应该类似于:
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();
这篇关于如何使用 Flutter 中的查询访问 Cloud Firestore 的数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!