【问题标题】:Firestore conditional where clause using Modular SDK v9使用 Modular SDK v9 的 Firestore 条件 where 子句
【发布时间】:2021-11-01 06:29:26
【问题描述】:

如何使用 Firebase Modular SDK (v9) 执行带有条件 where() 子句的查询?

名称空间版本 (v8) 中的示例查询:

const status = "live"
const publishedAfter = 1630607348811

let q = firebase.firestore().collection("articles")

// filters selected by users
if (status) q = q.where("status", "==", "live")
if (publishedAfter) q = q.where("publishedAt", ">", publishedAfter)

const qSnapshot = await q.get()

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    选项 1:有条件地添加 QueryConstraint,使用以前的作为基础

    let q = query(collection(firestore, "articles"))
    
    // filters selected by users
    if (status) q = query(q, where("status", "==", "live"))
    if (publishedAfter) q = query(q, where("publishedAt", ">", publishedAfter))
    
    const qSnapshot = await getDocs(q);
    

    选项 2:有条件地将 QueryConstraints 添加到数组中

    const constraints = []
    
    // filters selected by users
    if (status) constraints.push(where("status", "==", "live"))
    if (publishedAfter) constraints.push(where("publishedAt", ">", publishedAfter))
    
    const q = query(collection(firestore, "articles"), ...constraints)
    
    const qSnapshot = await getDocs(q);
    

    【讨论】:

    • 难以置信。 2 天后,我的头骨被这个破解了,我所要做的就是解构阵列......谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 2018-08-08
    • 2018-07-08
    • 2022-06-11
    相关资源
    最近更新 更多