按数字字段排序,其中时间戳位于 Cloud Firestore 中的给定日期?

sar*_*den 2 javascript google-cloud-firestore

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

{
  name: "Item 1",
  count: 2,
  timestamp: January 29, 2018 at 3:43:12 PM UTC-8
}
Run Code Online (Sandbox Code Playgroud)

我试图查询这个集合,以便文档按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);
Run Code Online (Sandbox Code Playgroud)

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

显而易见的解决方案是切换orderBy函数的顺序,以便按countthen排序timestamp,但是当我尝试执行此操作时,Firestore 引发了以下错误:

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

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

Dan*_*ath 5

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

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

const query = db.collection('items')
                .orderBy('count', 'desc')
                .where('date', '==', today);
Run Code Online (Sandbox Code Playgroud)