corysimmons
corysimmons

Reputation: 7685

How can I dynamically create Firebase Firestore Cloud Function queries?

I'm trying to dynamically generate queries.

I have a big object of things like location and price data. But I get that data from the request. How can I dynamically make use of that data if every query thing is a chained function?

Ideally I'd like to convert something like this...

const wheres = [
  { key: 'price', operator: '>=', value: '1000' },
  { key: 'price', operator: '<=', value: '2000' }
]

...to...

admin
      .firestore()
      .collection(`rentals`)
      .where(`price`, `>=`, `1000`)
      .where(`price`, `<=`, `2000`)

Upvotes: 4

Views: 2650

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317760

You don't have to chain everything directly with each other. The builder pattern used to build the query returns an instance of Query with each call to where() (and other filtering methods). The code you wrote is equivalent to this:

const collection = admin.firestore().collection('rentals')
var query = collection.where('price', '>=', '1000')
query = query.where('price', '<=', '2000')

You can keep working with query as much as you want like this. So, you should be able to keep appending more constraints to it in a loop or whatever suits your requirements.

Upvotes: 13

Related Questions