【问题标题】:How to use WhereIn in flutter with firestore?如何在 Firestore 中使用 WhereIn?
【发布时间】:2021-02-10 10:14:03
【问题描述】:

在电子商务颤振应用程序项目中,我使用我的项目集合的 shortInfo 字段作为每个产品的唯一 ID。当按下添加到购物车时,它会将shortInfo 保存到我的users 集合中一个名为userCartList 的数组字段中,我正在使用WhereIn 来查询这个数组,但是当我有超过10 个产品时,我的应用程序崩溃了。我在这里做错了什么?

这是我的 Firestore 结构:

Users Collection

Items Collection

这是我正在查询的一个 sn-p:

StreamBuilder<QuerySnapshot>( 
    stream: EcommerceApp.firestore
                        .collection("items")
                        .where("shortInfo", whereIn: EcommerceApp.sharedPreferences.getStringList(EcommerceApp.userCartList))
                        .snapshots()
)

【问题讨论】:

  • 你能提供导致错误的代码的sn-ps吗?
  • StreamBuilder( //TODO: 修复问题流:EcommerceApp.firestore .collection("items") .where("shortInfo", whereIn: EcommerceApp.sharedPreferences .getStringList(EcommerceApp. userCartList)) .snapshots(),
  • 此代码给出了所需的结果,但是当根据 firebase 规则添加超过 10 个产品时,此查询方法不允许超过 10 个,这就是导致错误的原因。用户购物车列表是保存在我从 firebase 检索的共享首选项中的列表

标签: firebase flutter google-cloud-firestore


【解决方案1】:

这里的问题是 Firestore 不允许您使用超过 10 条记录进行数组成员资格查询。如果您检查此documentation,您将看到:

使用 in 运算符将同一字段上的最多 10 个相等 (==) 子句与逻辑 OR 组合起来

在幕后,您的 whereIn 操作员正在执行文档中示例中显示的相同查询,如果您使用超过 10 条记录,Firestore 将不接受它,您将收到错误消息。我建议您将 EcommerceApp.userCartList 数组拆分为多个数组,最多 10 条记录进行查询,这将允许 Firestore 在其限制范围内操作 whereIn 并且它会起作用。

如果您对此问题还有任何疑问,请告诉我。

【讨论】:

  • 我能够使用以下代码解决此问题: for (int i = 1; i ( stream : EcommerceApp.firestore .collection("items") .where("shortInfo", isEqualTo: EcommerceApp.sharedPreferences .getStringList(EcommerceApp.userCartList)[i]) .snapshots(),
猜你喜欢
  • 2018-09-11
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
相关资源
最近更新 更多