Reputation: 2342
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.
Upvotes: 4
Views: 6883
Reputation: 42028
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);
Upvotes: 6