【问题标题】:Order by a number field where a timestamp is on a given date in Cloud Firestore?按 Cloud Firestore 中给定日期的时间戳的数字字段排序?
【发布时间】:2018-07-08 02:33:18
【问题描述】:

在我的 Firestore 数据库中,我的集合中有一些文档,如下所示:

{
  name: "Item 1",
  count: 2,
  timestamp: January 29, 2018 at 3:43:12 PM UTC-8
}

我正在尝试查询此集合,以便文档按count 降序排列,并且其timestamp 的日期等于今天的日期。

使用Moment.js,这是我目前的查询:

const startOfToday = moment().startOf('day').toDate();
const endOfToday = moment().endOf('day').toDate();

const query = db.collection('items')
                .orderBy('timestamp', 'desc')
                .orderBy('count', 'desc')
                .where('timestamp', '>=', startOfToday)
                .where('timestamp', '<=', endOfToday);

这个查询确实获取了以今天为timestamp 的日期的记录,但是它似乎首先按timestamp 对它们进行排序,如果两个具有相同的timestamp,然后它会排序count.

显而易见的解决方案是切换orderBy 函数的顺序,使其按count 然后timestamp 排序,但是当我尝试这样做时,Firestore 抛出了以下错误:

FirebaseError:查询无效。您有一个 where 过滤器在字段“timestamp”上有一个不等式( 或 >=),因此您还必须使用“timestamp”作为您的第一个 Query.orderBy(),但您的第一个 Query.orderBy( ) 而是在“计数”字段上。

如果有人有任何想法,我将不胜感激。

【问题讨论】:

  • 据我所知,不可能将一个字段上的范围过滤器与另一个字段上的 orderBy 结合起来。请参阅我和 Dan 的回答 here。您必须使用查询来过滤数据,然后在客户端重新排序。

标签: javascript google-cloud-firestore


【解决方案1】:

如 cmets 中所述,Cloud Firestore 不支持在范围过滤器和/或 order by 子句中使用多个字段。

但鉴于您的查询的性质,将其更改为相等过滤器(今天的日期)和按子句排序(计数)相对简单。您需要存储一个单独的字段,我们称之为date,它只包含日期(例如2018/01/30)而不是时间。然后您就可以查询为:

const query = db.collection('items')
                .orderBy('count', 'desc')
                .where('date', '==', today);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多