如何动态创建 Firebase Firestore Cloud Function 查询?

cor*_*ons 2 firebase firebase-security firebase-realtime-database google-cloud-firestore

我正在尝试动态生成查询。

我有一个很大的对象,比如位置和价格数据。但是我从请求中获得了这些数据。如果每个查询事物都是一个链式函数,我如何动态地利用这些数据?

理想情况下,我想转换这样的东西......

const wheres = [
  { key: 'price', operator: '>=', value: '1000' },
  { key: 'price', operator: '<=', value: '2000' }
]
Run Code Online (Sandbox Code Playgroud)

...到...

admin
      .firestore()
      .collection(`rentals`)
      .where(`price`, `>=`, `1000`)
      .where(`price`, `<=`, `2000`)
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 9

您不必将所有内容直接相互链接。用于构建查询的构建器模式在每次调用where()(和其他过滤方法)时返回一个Query实例。你写的代码等价于:

const collection = admin.firestore().collection('rentals')
var query = collection.where('price', '>=', '1000')
query = query.where('price', '<=', '2000')
Run Code Online (Sandbox Code Playgroud)

你可以query像这样继续工作。因此,您应该能够在循环中或任何适合您要求的内容中继续为其附加更多约束。