【问题标题】:How to access array index of Cloud Firestore using query in Flutter?如何在 Flutter 中使用查询访问 Cloud Firestore 的数组索引?
【发布时间】:2019-08-06 09:20:03
【问题描述】:

我在文档中有字段users,该字段包含数组中的两个元素。我必须检查特定的两个值是否在这个数组中。

首先,我为此使用了两次array-contains方法,但出现错误。

如何访问 Cloud Firestore 中数组字段的索引?

以下代码是我的方法,但它不起作用:

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

simple firestore structure

【问题讨论】:

    标签: firebase dart flutter google-cloud-firestore


    【解决方案1】:

    在 Firestore 中,您无法根据数组中存在的元素的索引来查询数据库。确实,您不能在查询中链接多个 array-contains 调用,但还有另一种解决方法可以帮助您实现相同的目标。因此,您的数据库结构需要进行更改。因此,您可以使用地图而不是使用数组,并且您的架构应该类似于以下内容:

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

    现在这样的查询可以正常工作了:

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

    【讨论】:

    • 本来我也想过这个方案。好,我知道了!谢谢!亚历克斯
    • 我没有达到可以投票的水平,但我现在可以投票了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2022-01-23
    • 2021-05-06
    相关资源
    最近更新 更多