Sachin Rathod
Sachin Rathod

Reputation: 573

How to query for Firebase timestamp field using AngularFire?

I am trying to retrieve all documents that has date field (type timestamp) less than current system time. AngularFirestore Query in my typescript file looks like this.

this.afs.collection<events>('events' , ref => ref.where('date' , '<' , Date.now())).snapshotChanges();

Above query doesn't contain any documents.

Help would be appreciated.

Upvotes: 0

Views: 932

Answers (1)

oiawo
oiawo

Reputation: 145

Just tested on my app, I guess you have Date (or actually a Timestamp) in your DB so you should compare the field to a Date Object :

this.afs.collection<events>('events' , ref => ref.where('date' , '<' , new Date())).snapshotChanges();

By the way, this might lead to strange behaviour if the user's device clock is off sync between he's devices or if the value is shared between users in different time frames. So the best practice is to use the serverTimestamp when putting the value to the field :

firebase.firestore.FieldValue.serverTimestamp()

When it comes to querying data, the firebase.firestore.FieldValue.serverTimestamp() method is not available so you are left with the following options :

  • Trusting the user's clock and using the new Date() mentioned or firebase.firestore.Timestamp.now(). In that case you can think of security rules to prevent users for cheating.
  • Using a callable cloud function to make specific and precise comparaison if they are necessary.

Overall I think the new Date() approach is the simplest and works in most cases.

Upvotes: 1

Related Questions