Home > Software design >  How can I query Firestore based upon an operation on a value in the document itself
How can I query Firestore based upon an operation on a value in the document itself

Time:11-11

I'm finding it hard to phrase, so let me try to lead with an example. Let's say I have a collection with documents containing an event time, and the number of hours before the event I wish to notify a person. Here is an example:

{
    personToNotify: DocumentReference(people/alex)
    hoursBeforeEvent: 5,
    eventTime: TimeStamp()
}

I currently have a cloud function running hourly - it pulls all documents to check. This would obviously be dreadful at scale. Is there a way to pull just the relevant documents? I.e. db.collection("events").where("hoursBeforeEvent", "==", TimeStamp - data.eventTime).get().

The time example is, of course, slightly tedious, but I've had similar issues in the past - so, is there a way to pull data based upon an operation performed on a different field of that document?

CodePudding user response:

There is no way to do calculations in Firestore queries. The value you want to order/filter on has to be the literal value of a field in the document.

I recommend adding a field notificationTime to the document, which you set upon writing the eventTime and/or hoursBeforeEvent, and then using that for your query.

  • Related