Firebase Firestore:如何订阅最近一小时创建的文档?

huangapple go评论61阅读模式
英文:

Firebase Firestore: How to subscribe to the last hour created documents?

问题

我需要创建一个Firestore订阅以获取在过去一小时内创建的文档。我在所有文档中都有一个"created-timestamp"字段。因此,订阅应该按照以下方式工作:如果文档停止被创建,随着时间的推移,结果捆绑包应该包含越来越少的文档(仅过去一小时相对于当前时间的筛选)。如何最好地完成这个任务?谢谢。

英文:

I have an Android app and I need make Firestore subscription to get docs created during the last hour. I have created-timestamp field in all docs. So the subscription should work like this: if docs stops to be created, over the time result bundle should contains less and less docs (filtering only the last hour relatively current time). What is the best way to do this? Thanks.

答案1

得分: 1

你不能使用 onSnapshot() 方法来监听集合,因为你的集合中的文档不会发生变化:在接收到初始查询快照后,快照处理程序将不会接收到任何新的快照(除非当然在其中一个文档中发生了其他更改)。

一种解决方法是每分钟获取一次集合。这可能会很昂贵。

另一种方法是使用云函数在文档创建后一小时更新文档中的特定标志,然后使用 onSnapshot(),因为在这种情况下文档会得到更新。

英文:

You cannot use the onSnapshot() method to listen to the collection because the docs in your collections do not change: After receiving the initial query snapshot the snapshot handler will not receive any new snapshot (unless another change occurs in one of the documents of course)

One solution is to fetch the collection every minute. This can be costly.

Another approach would be to use a Cloud Function to update a specific flag in the docs one hour after creation and use onSnapshot() because in this case the documents do get updated!

答案2

得分: 0

以下是翻译的内容:

没有办法使查询中的时间戳动态化,所以您需要在应用程序代码中从结果中删除已过期的文档。这需要两个步骤:

  1. 启动一个查询,以获取过去一小时内创建的文档。
  2. 在您的应用程序代码中持续删除已过期的文档。

查询本身应该相当简单:计算一小时前的时间戳,并在创建时间戳大于或等于该时间戳的文档上添加实时监听器

当您启动查询时,这将为您提供正确的文档,还会提供新文档。但由于查询中的时间戳是固定的,它不会删除过时的文档。

然后,您需要定期运行本地进程(例如每隔几秒钟)来检查您上次获取的结果中是否有过期的文档。

另请参阅:

英文:

There is no way to make the timestamp in the query dynamic, so you will have to remove the expired documents from the results in your application code.

This takes two steps:

  1. Start a query for the documents created in the past hour
  2. Continuously remove the expired documents in your application code

The query itself should be quite simple: calculate the timestamp of one hour ago, and add a realtime listener on documents with a creation timestamp greater or equal to that.

When you start the query this will give you the correct documents, and it will give you the new documents. But since the timestamp in the query is fixed, it won't remove the outdated documents.

Then you'll have to run a local process periodically (say every few seconds or so) to check for expired documents in the results you got last.

Also see:

huangapple
  • 本文由 发表于 2023年6月8日 19:15:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76431258.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定