首页 > 解决方案 > 使用 arrayContainsAny 进行 Flutter Firestore 查询:列表不起作用

问题描述

最新版本:Flutter + cloud_firestore:^0.14.0+2

代码:

      FutureBuilder(
      future: _sessionsLogCollection
          .where('companyId', isEqualTo: sPData.companyId)
          .where('locationId', arrayContainsAny: [
            '29L73oSzdQrzLUow3Mg9',
            'bugdWVC6RRtHoemuxNWE',
          ])
          // .where('locationId', isEqualTo: 'bugdWVC6RRtHoemuxNWE')
          .orderBy('openDateTime', descending: true)
          .get(),

我已经创建了索引,所以这不是问题。

单独使用.where('locationId', isEqualTo: 'bugdWVC6RRtHoemuxNWE')时,查询返回正确的数据。

但是单独使用.where('locationId', arrayContainsAny: ['29L73oSzdQrzLUow3Mg9','bugdWVC6RRtHoemuxNWE'])不会给出任何错误,而只是返回空数据集:sessionsSnapShot.data.documents.length: 0

** 使用 .whereIn 解决(可能 .whereIn 应该包含在 firebase.flutter.dev/docs/firestore/usage 中,因为它目前不存在)

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


根据您的代码.where('locationId', isEqualTo: 'bugdWVC6RRtHoemuxNWE'),这似乎locationId不是一个数组,而是一个字段。如果要查询数组,只能使用arrayContainsand arrayContainsAny。但由于这是一个字段,因此您必须使用whereIn

          .where('locationId', whereIn: [
            '29L73oSzdQrzLUow3Mg9',
            'bugdWVC6RRtHoemuxNWE',
          ])

使用 in 运算符可将同一字段上的最多 10 个相等 (==) 子句与逻辑 OR 组合在一起。in 查询返回给定字段与任何比较值匹配的文档

https://firebase.google.com/docs/firestore/query-data/queries#array_membership

https://github.com/FirebaseExtended/flutterfire/blob/master/packages/cloud_firestore/cloud_firestore/lib/src/query.dart#L393


推荐阅读