Order by a number field where a timestamp is on a given date in Cloud Firestore?

时光毁灭记忆、已成空白 提交于 2021-01-27 21:23:42

问题


In my Firestore database I have some documents in a collection that look like this:

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

I'm trying to query this collection such that the documents are ordered by count in descending order, AND have their timestamp's date equal to today's date.

Using Moment.js, this is the query I have so far:

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);

And this query does indeed fetch the records that have today as their timestamp's date, however it appears to be ordering them by timestamp first, and if two had the same timestamp, it would then order by count.

The obvious solution would be to switch the order of the orderBy functions so it would order by count then timestamp, but when I tried doing this Firestore threw the following error:

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.

If anyone has any ideas, I would really appreciate it.


回答1:


As mentioned in the comments, Cloud Firestore does not support using more than a single field in range filters and/or order by clauses.

Given the nature of your query though, it is relatively simple to change it to an equality filter (today's date) and order by clause (count). You'll need to store a separate field, let's call it date, that just contains the date (e.g. 2018/01/30) and not the time. You'll then be able to query as:

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


来源:https://stackoverflow.com/questions/48500547/order-by-a-number-field-where-a-timestamp-is-on-a-given-date-in-cloud-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!