javascript - 访问 Google Firestore 集合的最后 N 个文档
问题描述
我想从 google firestore 集合中访问最后 N 个文档。文档的关键是 ISO 格式的时间戳。集合首先需要根据时间戳键进行排序,并且要检索最后更新的 N 个文档。此操作必须是实时且快速的。
events(collection) =>
documents as below:
2019-01-07T08:21:18.600Z => {
symbolname: '10900CE',
price: '10825.0',
timestamp: '2019-01-07T13:51:18Z',
quantity: '2.0',
side: 'SELL' }
2019-01-07T08:21:28.614Z => {
symbolname: '10800PE',
price: '10825.0',
timestamp: '2019-01-07T13:51:28Z',
quantity: '2.0',
side: 'BUY' }
2019-01-07T09:45:24.783Z => { side: 'SELL',
symbolname: '10800PE',
price: '10805.0',
timestamp: '2019-01-07T15:15:24Z',
quantity: '2.0' }
我目前遍历集合并将键添加到数组中,然后对数组进行排序并通过这些键获取最后 N 个文档,如下所示:
var ids = []
db.collection('events').get()
.then((snapshot) => {
snapshot.forEach((doc) => {
ids.push(doc.id)
});
})
.then(()=>{
//sortIds(ids);
console.log(JSON.stringify(ids[ids.length-2])) //second last entry 2019-01-07T08:21:28.614Z
})
.catch((err) => {
console.log('Error getting documents', err);
});
如果集合大小增加,此操作需要很长时间。是否有实现此目的的最佳方法(排序/orderBy-descending 集合并获取最后 N 个文档)?
谢谢
解决方案
也许是这样的:
db.collection('events').orderBy("timestamp").limit(n)
推荐阅读
- python - python等价于Matlab展平
- python - 过滤电话号码
- foreach - Swiftui Identifiable Foreach 循环能否仅选择前 5 个项目
- kubernetes - 卷 GKE 磁盘大小无效
- typescript - vscode自动导入创建打字稿抱怨的文件路径不存在
- python - 如何使从烧瓶中的 API 检索到的数据显示在新的 html 中?
- css - 悬停时将元素旋转 50%,悬停时继续沿相同方向旋转(仅限 CSS)
- c++ - C++ int 指针追溯地取消引用 self
- office-js - 在 Exchange 服务器中搜索返回所有项目并忽略搜索限制
- javascript - XMLHttpRequest 对象按钮单击仅加载第一个子节点???如何获得所有节点?