【问题标题】:How to sort by a field in a sub-collection in firebase cloud firestore in flutter如何在 flutter 中按 firebase 云 Firestore 的子集合中的字段排序
【发布时间】:2023-01-15 01:58:13
【问题描述】:
我正在尝试查询云 firestore 数据库,我需要它返回聊天集合中的所有文档,这些文档按时间戳字段排序,该字段是消息子集合中的所有文档都具有的字段。
我试过写这样的查询。
FirebaseFirestore.instance.collection("chats").orderBy("messages.timestamp", descending: true)].get(),
但是当实际上那里有一些文件时它不会返回任何文件。
【问题讨论】:
标签:
flutter
firebase
google-cloud-firestore
【解决方案1】:
Firestore 只能对它返回的文档中的数据进行排序或过滤。无法对这些文档之外的数据进行排序或过滤。
因此,如果我们想在该聊天中的最后一条消息的时间戳中对聊天进行排序(常见用例),则必须在聊天文档本身中包含一个 lastMessageTimestamp 字段,并在写入消息时更新该字段在其messages 子集合中。在每个 chats 文档中都有该 lastMessageTimestamp 字段,然后您可以对其进行排序和过滤。