Firestore 查询中的条件 where 子句

IT技术 javascript firebase google-cloud-firestore
2021-03-06 19:55:12

我已经从 firestore 获取了一些数据,但在我的查询中我想添加一个条件 where 子句。我正在为 api 使用 async-await,但不确定如何添加条件 where 子句。

这是我的功能

export async function getMyPosts (type) {
  await api
  var myPosts = []

  const posts = await api.firestore().collection('posts').where('status', '==', 'published')
    .get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.data())
      })
    })
    .catch(catchError)
}

在我的主函数中,我得到了一个名为“type”的参数。根据该参数的值,我想向上述查询添加另一个 qhere 子句。例如,if type = 'nocomments'然后我想添加一个 where 子句。where('commentCount', '==', 0), 否则if type = 'nocategories', where 子句将查询另一个属性,如.where('tags', '==', 'none')

我无法理解如何添加这个条件 where 子句。

注意:在 firestore 中,您只需添加像 - 这样的 where 子句即可添加多个条件。where("state", "==", "CA").where("population", ">", 1000000)等等。

1个回答

仅在需要时将 where 子句添加到查询中:

export async function getMyPosts (type) {
  await api
  var myPosts = []

  var query = api.firestore().collection('posts')
  if (your_condition_is_true) {  // you decide
    query = query.where('status', '==', 'published')
  }
  const questions = await query.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.data())
      })
    })
    .catch(catchError)
}
这在新的firestore中仍然有效吗?集合,它有“where”方法还是通过“ref”父对象?
2021-04-20 19:55:12
如何动态查询 = query.doc(myId)?我已经尝试过这个例子并且使用where子句而不是doc
2021-05-01 19:55:12