Firestore 按时间排序但按 ID 排序 [英] Firestore order by time but sort by ID

查看:21
本文介绍了Firestore 按时间排序但按 ID 排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图找出一种方法来查询文档列表,其中我在一个字段上有一个范围过滤器并按另一个字段排序,这当然是不可能的,请参阅我的另一个问题:

任何想法如何存储文档,以便它们在集合中按创建顺序排序?

解决方案

Firebase 控制台中显示的文档顺序与使用 Firestore 的代码的功能几乎无关.控制台仅用于浏览数据,如果您知道文档 ID,那么这种排序方案可以相对直观地找到您可能正在查找的文档.您无法在控制台中更改此排序顺序.

您的代码显然会有其他要求,这些要求应该编码到您的查询中,而不考虑您在仪表板中看到的任何排序顺序.如果您希望对文档进行基于时间的排序,则必须在文档中存储某种时间戳字段,并将其用于排序.我不建议使用时间戳作为文档的 ID,因为这可能会在以后给您带来问题.

I have been trying to figure out a way to query a list of documents where I have a range filter on one field and order by another field which of course isn't possible, see my other question: Order by timestamp with range filter on different field Swift Firestore

But is it possible to save documents with the timestamp as id and then it would sort by default? Or maybe hardcode an ID, then retrieve the last created document id and increase id by one for the next post to be uploaded?

This shows how the documents is ordered in the collection

Any ideas how to store documents so they are ordered by created at in the collection?

解决方案

The order of the documents shown in the Firebase console is mostly irrelevant to the functioning of your code that uses Firestore. The console is just for browsing data, and that sorting scheme makes it relatively intuitive to find a document you might be looking for, if you know its ID. You can't change this sort order in the console.

Your code is obviously going to have other requirements, and those requirements should be coded into your queries, without regarding any sort order you see in the dashboard. If you want time-based ordering of your documents, you'll have to store some sort of timestamp field in the document, and use that for ordering. I don't recommend using the timestamp as the ID of a document, as that could cause problems for you in the future.

这篇关于Firestore 按时间排序但按 ID 排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆