Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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`)
like image 696
corysimmons Avatar asked Oct 27 '25 12:10

corysimmons


1 Answers

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.

like image 138
Doug Stevenson Avatar answered Oct 30 '25 04:10

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!