1

Please advise how to query firestore collection on timestamp field?

Query below returns nothing even if there are multiple documents with filled date field (timestamp type) exist in db:

db.collection("users").doc('john').
         collection("comment").
         where("date", ">", 0).
         get() 
user947668
  • 2,548
  • 5
  • 36
  • 58
  • 1
    For you to be able to query using date fields, you need to compare a date - in this case, the `date` field from your document - to a date as well. The `0` is not considered a 0, so this is probably affecting your comparison. Could you please change the part `where("date", ">", 0)` to something like `where("date", ">", new Date())`? This way, you should be doing comparions between `Date` type fields. – gso_gabriel Jun 22 '20 at 06:30
  • @gso_gabriel thank you, so in order to compare db timestamp with epoch timestamp I have to use something like `where("date", ">", new Date(epoch*1000))` – user947668 Jun 22 '20 at 08:18
  • 1
    Hi @user947668 yes, exactly. This way, you will be convering to an aproximate date - which might make sense considering your structure, I can't be sure - but yes, this way it should work. More examples of conversion of `timestamps` in Firestore can be found [here](https://stackoverflow.com/questions/52247445/how-do-i-convert-a-firestore-date-timestamp-to-a-js-date). Let me know if it helped you and if you think it's okay for me to post an answer about my assistance here, so you could accept or upvote, to help future users from the Community. :) – gso_gabriel Jun 22 '20 at 08:42
  • 1
    @gso_gabriel i checked query and it works as expected. you can post it as an answer. Thank you for your assistance – user947668 Jun 22 '20 at 09:32

1 Answers1

1

For you to be able to query using date fields, you need to compare a date - in this case, the date field from your document - to a date as well. The 0 is not considered a number 0, so this affects the comparison.

It needs to be something like this: where("date", ">", new Date()). In case you want to compare dates based in epoch timestamp, a good solution is convert the new date using the where like this: where("date", ">", new Date(epoch*1000)) as mentioned. Once you using comparison in the where part of the query, the returns should occur correctly.

Besides that, more examples of converting timestamps for Firestore can be found here.

gso_gabriel
  • 4,199
  • 1
  • 10
  • 22