javascript - 按时间戳在 Cloud Firestore 中给定日期的数字字段排序?

标签 javascript google-cloud-firestore

在我的 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: Invalid query. You have a where filter with an inequality (<, <=, >, or >=) on field 'timestamp' and so you must also use 'timestamp' as your first Query.orderBy(), but your first Query.orderBy() is on field 'count' instead.

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

最佳答案

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

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

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

关于javascript - 按时间戳在 Cloud Firestore 中给定日期的数字字段排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48500547/

相关文章:

javascript - firebase 函数在 onCreate firestore 事件中删除了错误流

javascript - 将类添加到包含特定宽度图像的 div

javascript onclick create(element) div viz弹出框

javascript - jquery animate 在滑动之前将 div 推到下面

reactjs - Firestore 按数组的字段值查询

java - 根据文档列表查询 FireStore

javascript - 获取网页上使用 TAB 按钮选择的项目的标题

javascript - 从 PHP 查询中获取 JSON 数组后,使用 javascript 将其写入 html 页面

java - 如何将 FireStore 逻辑分离到自己的类中

arrays - Firestore 数组中的排序顺序