使用 Modular SDK v9 的 Firestore 条件 where 子句

2023-12-22

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

名称空间版本 (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()

选项 1:有条件添加QueryConstraint https://firebase.google.com/docs/reference/js/firestore_.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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Modular SDK v9 的 Firestore 条件 where 子句 的相关文章

随机推荐