0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

how to retrieve data using serverTimestamp() as I am getting this error Function Query.where() called with invalid data. FieldValue.serverTimestamp() can only be used with update() and set()
Ok, so it seems that I was wrong, I updated the answer to better explain this Also I added a new possibility : firebase.firestore.Timestamp.now()
Can you please also explain how this can be achieved using callable cloud function? I don't want to depend on user device clock since user may time fake/cheat.
Callable functions are basically replacing the need for a server API with a layer of authentication. The following documentation will help you setting this up : firebase.google.com/docs/functions/callable Inside of a callable function, you can use basically the same request, with the difference is that new Date() will be the server's date. Be aware that Firebase functions are a paid service so check this out before starting in this direction (firebase.google.com/pricing).
Yes I have maintained that rule in my security rules.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.