Luciano Marqueto
Luciano Marqueto

Reputation: 1198

How to use firestore.FieldValue.serverTimestamp() in query

I want to create a query in the google cloud firestore to retrieve the data created in the last 10 hours, but I would like to use the server date as the basis for the account.

Something like:

this.afs.collection<any>("posts/", ref => {
  let query: firebase.firestore.CollectionReference | firebase.firestore.Query = ref;

  tenHoursAgo = firebase.firestore.FieldValue.serverTimestamp() - 10; 
  query = query.where('created', '>', tenHoursAgo);

  return query.orderBy('created');
}).snapshotChanges()

How can i do this? thanks for any help.

Upvotes: 3

Views: 1940

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600130

You can't use FieldValue.serverTimestamp() as a value in a query.

Two possible workarounds for this:

  1. The simplest way to get close is to use use a local current timestamp of the client: new Date().

  2. The more complex alternative is to have the client write a FieldValue.serverTimestamp(), then read that back, and use the resulting value in your query.

    This would isolate you from impact of any skew in the client's clock. Whether that is worth the extra complexity is up to you to decide.

Upvotes: 4

Related Questions