【问题标题】:Conditional where clause in firestore queriesFirestore 查询中的条件 where 子句
【发布时间】:2018-07-08 22:56:01
【问题描述】:

我已经从 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)
}

在我的主要功能中,我得到了一个名为“类型”的参数。基于该参数的值,我想在上述查询中添加另一个 qhere 子句。比如if type = 'nocomments',那么我要添加一个where子句.where('commentCount', '==', 0),否则if type = 'nocategories',那么where子句将查询另一个属性如.where('tags', '==', 'none')

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

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

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案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)
    }
    

    【讨论】:

    • 如何动态查询 = query.doc(myId)?我已尝试使用此示例并使用 where 子句但不适用于 doc
    • 这在新的 Firestore 中仍然有效吗?集合,它有一个“where”方法还是通过“ref”父对象?
    猜你喜欢
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 2012-04-20
    相关资源
    最近更新 更多