在我的 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/