首页 > 解决方案 > Firestore Timestamp 获取不等于特定日期的集合文档

问题描述

我有一个 Firestore 数据库,其中包含集合中的文档列表。每个文档都有一个预定的日期,它是一种“时间戳”数据类型。我能够在预定日期之前获取数据,但无法获取不等于特定预定日期的所有文档。所以我所做的是在前端过滤了所有不等于预定日期的数据,但是有一个权衡我必须将所有收集文档存储在前端

下面的查询用于按预定日期获取数据。

where: [
        [
          'ScheduleDateTime',
          '>=',
          new Date('2020-02-12 00:00:00'),
        ],
        [
          'ScheduleDateTime',
          '<=',
          new Date('2020-02-12 23:59:59'),
        ],
      ],

逻辑我内置了不相等日期的前端。

const Quotations =
    allDocuments.filter(
      ele =>
        scheduledDateList.indexOf(
          ele.id
        ) == -1
    );

我们已经知道我们不能在 Firestore 中使用!=OR调节。在firestore上工作非常困难。任何建议或解决方案都会有所帮助。

标签: reactjsfirebasegoogle-cloud-firestoreredux-firestore

解决方案


正如您在问题中提到的,以及文档中的解释:

Cloud Firestore 不支持以下类型的查询:

  • …</li>
  • 不支持带有!=子句的查询。在这种情况下,将查询拆分为大于查询和小于查询。...
  • 逻辑查询。在这种情况下,您应该为每个 OR 条件创建一个单独的查询,并在您的应用程序中合并查询结果

以下函数将根据ScheduleDateTime时间戳字段合并两个查询:

  async function getDatesNotEqual() {

    const isLess = datesRef
      .where(
        'ScheduleDateTime',
        '<=',
        firebase.firestore.Timestamp.fromDate(
          new Date('2020-02-12 00:00:00')
        )
      )
      .get();

    const isMore = datesRef
      .where(
        'ScheduleDateTime',
        '>',
        firebase.firestore.Timestamp.fromDate(
          new Date('2020-02-12 23:59:59')
        )
      )
      .get();

    const [isLessQuerySnapshot, isMoreQuerySnapshot] = await Promise.all([
      isLess,
      isMore
    ]);

    const isLessThanDocsArray = isLessQuerySnapshot.docs;
    const isMoreThanDocsArray = isMoreQuerySnapshot.docs;

    return _.concat(isLessThanDocsArray, isMoreThanDocsArray);
  }


  //Here we call the async function
  getDatesNotEqual().then(result => {
    result.forEach(docSnapshot => {
      console.log(docSnapshot.data());
    });
  });

请注意,我们使用Lodash库来合并两个数组 ( _.concat()),但您可以使用其他技术来这样做。


另请注意,我们使用fromDate()Firestore 的方法Timestamp来构建查询。


推荐阅读