Firestore 查询中的条件 where 子句 [英] Conditional where clause in firestore queries

查看:36
本文介绍了Firestore 查询中的条件 where 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have fetch some data from firestore but in my query I want to add a conditional where clause. I am using async-await for api and not sure how to add a consitional where clause.

这是我的功能

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

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. For example, if type = 'nocomments', then I want to add a where clause .where('commentCount', '==', 0), otherwise if type = 'nocategories', then the where clause will be querying another property like .where('tags', '==', 'none')

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

I am unable to understand how to add this conditional where clause.

注意:在 firestore 中,您可以通过附加 where 子句来添加多个条件,例如 - .where("state", "==", "CA").where("population", ">",1000000) 等等.

NOTE: in firestore you add multiple conditions by just appending your where clauses like - .where("state", "==", "CA").where("population", ">", 1000000) and so on.

推荐答案

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

Add the where clause to the query only when needed:

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 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆