Firebase Query by Date String

Cloud Functions Query Date from Firestore field which is a String

First off, the condition you pass to you query is wrong because you need to pass:

  1. The field name to filter on in the first parameter, which is now moment("reqDate").format('MM/DD/YYYY'), but should be "reqDate".
  2. The operator, which is correct in your code.
  3. The value to filter on.

This date format you use is unsuitable for range filters, since strings are ordered lexicographically and in that order: "10/05/2021" is before "11/05/2020".

To allow a range query, you need a date format that allows for that. When the date is a string, the most common formats are based on ISO-8601, such as "2021-10-17", because in this format dates that are after October 17 are queryable with: .where("reqDate", ">", "2021-10-17")

Firestore query by date

You will need a range query with start and end points to cover the intended time. In Firestore, timestamp types are always considered a single point in time and do not have date and time components available. It's the same for Date objects in JavaScript.

refWallet
.where("dateStart", ">=", startDate)
.where("dateStart", "<", endDate)
.get()

If this is not what you want, then you probably shouldn't use a timestamp type field and instead use a string that will give you an exact match. For example, you could store dates as strings formatted YYYYMMDD in order to query for exact dates without ranges.

Flutter Firestore query by date and String simultaneously not returning?

The problem is that you have to define an index for this query to be performed in the Firestore.

Log the whole catched exception and you will see a link in the exception, open it in the browser and it will navigate you to a page in Google Cloud Console where you can just click on Create to create the required index, after that you should just wait for the index to be created and then run the query again and you will see that every thing works fine.

To learn more about Firestore indexes, follow this link.



Related Topics



Leave a reply



Submit