简体   繁体   English

Firestore 查询中的条件 where 子句

[英]Conditional where clause in firestore queries

I have fetch some data from firestore but in my query I want to add a conditional where clause.我已经从 firestore 获取了一些数据,但是在我的查询中我想添加一个条件 where 子句。 I am using async-await for api and not sure how to add a consitional where clause.我正在为 api 使用 async-await,但不确定如何添加条件 where 子句。

Here is my function这是我的功能

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)
}

In my main function I am getting a param called 'type'.在我的主要功能中,我得到了一个名为“类型”的参数。 Based on the value of that param I want to add another qhere clause to the above query.基于该参数的值,我想在上述查询中添加另一个 qhere 子句。 For example, if type = 'nocomments' , then I want to add a where clause .例如, if type = 'nocomments' ,那么我想添加一个 where 子句。 where('commentCount', '==', 0) , otherwise if type = 'nocategories' , then the where clause will be querying another property like .where('tags', '==', 'none') where('commentCount', '==', 0) ,否则if type = 'nocategories' ,那么 where 子句将查询另一个属性,例如.where('tags', '==', 'none')

I am unable to understand how to add this conditional where clause.我无法理解如何添加这个条件 where 子句。

NOTE: in firestore you add multiple conditions by just appending your where clauses like - .注意:在 firestore 中,您只需添加 where 子句,如 - 即可添加多个条件。 where("state", "==", "CA").where("population", ">", 1000000) and so on. where("state", "==", "CA").where("population", ">", 1000000)等等。

Add the where clause to the query only when needed:仅在需要时将 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)
}

For the frontend Web SDK:对于前端 Web SDK:

Or you can look at this link for a different method: Firestore conditional where clause using Modular SDK v9或者您可以查看此链接以了解其他方法: Firestore conditional where Clause using Modular SDK v9

 let showPublishStatus: boolean = true let conditionalConstraint: QueryConstraint = showPublishStatus ? where("status", "==", "published") : where("status", "!=", "published") let queryWebSDK = query(collection(db, "Collection"), conditionalConstraint)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM