firestore查询中的条件where子句 [英] Conditional where clause in firestore queries
问题描述
我从firestore获取了一些数据但在我的查询中我想添加一个条件where子句。我正在使用async-await for api而不确定如何添加consitional 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子句。例如,如果type ='nocomments'
,那么我想添加一个where子句。 where('commentCount','==',0 )
,否则如果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屋!