Firebase querying by date range always returns empty array

Viewed 649

In my database I have all the documents saved on the day 23 of this month as the image below shows

enter image description here

Even if i pass the start date in day 20 it will return empty value.

Here is my query snippet:

const documents = await admin.firestore()
    .collection('orders')
    .orderBy('payment_type')
    .startAt('2020-06-22')
    .endAt('2020-06-23')
    .get()

I'm new to firebase, so I don't know where i'm missing and the docs were not much of help. Also, i'm using cloud functions if the information helps.

2 Answers

The value you pass to startAt and endAt has to correspond to the fields you're using for ordering. Since you're ordering on payment_type, the start and end values don't make sense - they are looking for ranges of values that don't match at all payment_type values at all. Also, it doesn't make sense to use startAt and endAt unless you are trying to do pagination, which it doesn't look like you are here.

If you're trying to do a range query between two dates, then order the results by payment_type, that's actually not possible with Firestore using the data you have now. You can't have a range query on a field that's different than the fields you're using to order. Note the limitation in the documentation:

If you include a filter with a range comparison (<, <=, >, >=), your first ordering must be on the same field:

citiesRef.where("population", ">", 100000).orderBy("population")

So, you can try a range query by date:

const documents = await admin.firestore()
    .collection('orders')
    .where('date', '>', '2020-06-22')
    .where('date', '<', '2020-06-23')
    .get()

The order the results on the client by payment_type if you want.

You're ordering by payment_type, which isn't a date value. Suggest you update that to date instead so that the respective startAt and endAt functions will target the correct field. Documentation

const documents = await admin.firestore()
    .collection('orders')
    .orderBy('date')
    .startAt('2020-06-22')
    .endAt('2020-06-25')
    .get()

Also, extend the value of your endAt to encompass June 24th.

Related