Udith Gunaratna
Udith Gunaratna

Reputation: 2111

Firebase Firestore order by 2 fields conditionally

I have some documents in Firestore with two Timestamp fields named lastUpdated and lastProcessed in addition to other fields. lastUpdated field is updated when a user updates the record's fields via web console. lastProcessed field is updated when the backend function processes the document (as a result of user clicking a button).

Following are the possible combinations of these 2 fields.

  1. User has only updated the document, but yet to process (lastUpdated == some_timestamp, lastProcessed == '')
  2. User has updated the document, and then processed (lastUpdated < lastProcessed)
  3. User has updated the document, processed and re-updated (lastUpdated > lastProcessed)

My requirement is to execute a query to get a subset of these records (say top 10), ordered by its most recent timestamp. So when evaluating a record for the ordering, lastUpdated field should be considered for scenarios 1 and 3 above. But lastProcessed field should be considered for scenario 2.

Is this possible with Firestore?

Upvotes: 0

Views: 94

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83068

When querying the Firestore database it is not possible to execute the logic you explain in your question (i.e. calculate on the fly the scenario to be applied and define which field shall be used in the query).

One classical solution is to add an extra field to the document which contains the value to be queried for. The value of this field can be calculated (according to the business logic) when you modify the document from your frontend, or via a Cloud Function triggered in the backend each time the doc is changed.

The main advantage of using a Cloud Function is to prevent users modifying the value of this field.

Upvotes: 1

Related Questions