繁体   English   中英

尝试在查询中订购 Firestore 结果

[英]Trying to order Firestore results in query

我有一个查询,我想按开始日期排序并按结束日期过滤。

return FirebaseFirestore.instance
        .collection("content")
        .where("active", isEqualTo: true)
        .where("end", isGreaterThanOrEqualTo: DateTime.now())
        .orderBy("start", descending: true)
        .snapshots();

错误:

当不等运算符时,初始 orderBy() 字段 '[[FieldPath([start]), true]][0][0]' 必须与 where() 字段参数 'FieldPath([end])' 相同被调用。

如果您包含一个带有范围比较(<、<=、>、>=)的过滤器,您的第一个排序必须在同一个字段上

https://firebase.google.com/docs/firestore/query-data/order-limit-data#limitations

所以你应该 go 与

return FirebaseFirestore.instance
        .collection("content")
        .where("active", isEqualTo: true)
        .where("end", isGreaterThanOrEqualTo: DateTime.now())
        .orderBy("end", descending: true)
        .orderBy("start", descending:true)
        .snapshots();

您收到以下错误:

当不等运算符时,初始 orderBy() 字段 '[[FieldPath([start]), true]][0][0]' 必须与 where() 字段参数 'FieldPath([end])' 相同被调用。

因为在使用不等运算符时,如果不先对end字段进行排序,就无法从 Firestore 获取数据。 因此,您需要在应用程序代码中对结果重新排序。 所以在调用之后:

.where("end", isGreaterThanOrEqualTo: DateTime.now())

必须调用:

.orderBy("end", descending:false)

所以你的查询应该是这样的:

return FirebaseFirestore.instance
    .collection("content")
    .where("active", isEqualTo: true)
    .where("end", isGreaterThanOrEqualTo: DateTime.now())
    .orderBy("end", descending:false)
    .orderBy("start", descending:true)
    .snapshots();

也不要忘记创建索引以使该查询有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM