【问题标题】:Flutter & Firestore: How do I get the most recent first?Flutter & Firestore:我如何首先获得最新的?
【发布时间】:2021-03-08 10:54:48
【问题描述】:

如何从 Firestore 获取最新的第一个?

FirebaseFirestore.instance.collection(Strings.factsText)
                .where(
                    Strings.category,
                    whereIn: [Strings.climateChange])
                    .orderBy('timestamp', descending: true)
                    .snapshots(),
               
                    ...
                  final factsDocs = snapshot.data.documents;
                  return FactsListContainer(factsDocs: factsDocs);
                });

.orderBy 一起使用时,问题似乎出在.where

【问题讨论】:

  • 嗨。你没有带日期的字段?还是按字母顺序排列的字段?如果是,您可以使用 .orderBy("date", Query.Direction.DESCENDING) 订购数据,然后使用 .limit(1) 获取第一个数据
  • @ande 嗨,我尝试添加一个 createdAt 字段,但是当我尝试将 orderBy 与我的代码合并时,我无法让它工作。你能告诉我它如何与我在这里提供的代码一起工作吗?
  • 我不是颤振专家(firestore 更多),但您可以看到stackoverflow.com/questions/58154176/… 并在添加查询后添加 .limit(1)。对我来说它将是 .collection(Strings.factsText).where(...).orderBy("createdAt", descending: true).limit(1).snapshots()
  • @ande 谢谢。这是我之前尝试过的,但出现错误:getter 'documents' was called on null
  • 你确定你的“Strings.factsText”是一个集合吗?

标签: firebase flutter google-cloud-firestore


【解决方案1】:

如果您有一个带有时间戳的createdAt 字段,或者一个始终递增的值,您可以按该字段的降序获取快照:

stream: FirebaseFirestore.instance
  .collection(Strings.factsText)
  .orderBy('timestamp', descending: true)
  .where(
    Strings.category,
    whereIn: [Strings.climateChange])
    .snapshots(),

另请参阅Query.orderBy method 上的 FlutterFire 文档。

【讨论】:

  • 谢谢。这是我之前尝试过的,但出现错误:getter 'documents' was called on null
  • 如果该错误仅在您添加 orderBy 调用后发生,听起来您的文档没有 timestamp 字段。
  • 我已经仔细检查过,它们都有时间戳字段。
  • 您能否编辑您的问题以显示您希望在snapshots 中出现的文档之一?
【解决方案2】:

我终于通过在 Firebase 控制台中创建一个索引解决了这个问题,而且效果很好,所以现在我首先得到最新的。

在我的数据库中,我去索引创建一个新索引,添加我的集合名称,然后对于我添加“类别” - 降序和“时间戳” - 降序的字段,单击集合,然后单击创建索引。

【讨论】:

  • 我在 vs 代码编辑器中没有收到任何请求/错误来创建 index。我们如何删除已经在 Firestore 上创建的indexes?有什么建议吗?非常感谢。
猜你喜欢
  • 2022-01-08
  • 2020-01-04
  • 2019-12-09
  • 2021-11-04
  • 2018-03-13
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多