[英]Conditional where clause in firestore queries
我已經從 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)
等等。
僅在需要時將 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)
}
對於前端 Web SDK:
或者您可以查看此鏈接以了解其他方法: 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.