【问题标题】:How to return documents which were created between 2 timestamps using Firestore如何使用 Firestore 返回在 2 个时间戳之间创建的文档
【发布时间】:2020-03-04 08:24:32
【问题描述】:

我想从我的收藏中加载保存在两个时间戳之间的所有文档。我在我的 component.ts 中调用了一个服务函数,我在其中将我需要的 2 个时间戳设置为参数。我如何查询数据库以便使用 ref.where 返回我想要的文档

此功能位于我的服务中

findItems(colId: string, timestamp1: Date, timestamp2: Date){
    return this.db.collection(`items/${colId}/stuff`,ref =>{
      return ref.where("createdAt", ">=", startTime );
        }).valueChanges()
    } 

我在上面的组件中调用了这个函数

  public items: Observable<any>

this.myService.findItems(this.item.colId, this.item.time1, this.item.time2)

一项的实际字段:

开始/结束时间戳示例:

【问题讨论】:

  • 将 where 子句与范围 on the same field 结合起来应该不会有任何问题。但是,您需要使用 createdAt 字段创建数据,因为默认情况下 Firestore 不会为其文档添加时间戳。您的代码中startTime 的来源也不清楚。
  • 我会尝试 ref.where("createdAt",">=",timestamp1).where("createdAt","
  • 如果它不起作用(我注意到您现在查询的字段名称是created 而不是createdAt,请显示您数据库中的一些数据)。您也可能无法直接与 Date 对象进行比较。
  • 我检查了时间戳,因为我将它们转换为 Firestore 格式的时间戳。我通过数据库界面手动添加了一些,从我的应用程序中添加了一些,并且外观相同。我将在我的帖子中提供一些照片
  • 不清楚这些图像是什么,甚至字段名称应该是什么(现在也有带有startTimeendTime 的字段。请显示更多上下文。

标签: angular firebase google-cloud-firestore timestamp angularfire


【解决方案1】:

只要涉及only one field,在Firestore 中使用字段范围创建复合查询是完全可以的。这样做,你应该没有问题。

假设 createdAt 字段正在此集合中的所有文档上创建为时间戳字段,并且 timestamp1 始终小于 timestamp2,则此代码应生成一个查询,该查询可以满足您的需求并返回您需要的Observable

findItems(colId: string, timestamp1: Date, timestamp2: Date) {
    return this.db.collection(`items/${colId}/stuff`, ref => {
        return ref.where('createdAt', '>=', firestore.Timestamp.fromDate(timestamp1))
                  .where('createdAt', '<=', firestore.Timestamp.fromDate(timestamp2));
        }).valueChanges()
    } 

假设您已导入 firestore 命名空间,这在 AngularFire 中有效,如下所示:

import { firestore } from 'firebase';

有更完整的文档说明它如何适应 AngularFire here,尽管 ValueChanges 的文档及其注意事项(例如不返回文档 ID)是 here

【讨论】:

  • 使用复合查询效果很好。我是否需要在此服务调用之后订阅它 -> this.myService.findItems(this.item.colId, this.item.time1, this.item.time2) 才能查看项目?
  • 与您的原始函数一样,它为基于数据的 JSON 对象的同步数组返回一个 Observable,因此您可以像 Observable 那样以任何方式使用它。 AngularFire 文档有一个great example 说明如何使用来自valueChanges() 的结果。
  • 简短回答:是的,您有时需要订阅它,但您可以在模板中使用它,例如。
猜你喜欢
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 2019-08-14
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-23
相关资源
最近更新 更多