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

标签 javascript firebase google-cloud-firestore

如何使用条件查询 where()使用 Firebase Modular SDK (v9) 的子句?
namespace 版本 (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 使用先前作为基础

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

关于javascript - 使用 Modular SDK v9 的 Firestore 条件 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69036031/

相关文章:

firebase - Firestore 对子集合的规则

javascript - 无法使用 FieldValue.increment 方法

javascript - 如何更新数组字段?

javascript - 获取 NaN 而不是数字/值

javascript - 单击按钮显示另一个按钮组?

javascript - A-tag 中的 Fire Click 事件

firebase - 无法通过 `CompileOptions.compilerArgs` 指定 -processorpath 或 --processor-path。请改用 `CompileOptions.annotationProcessorPath` 属性

javascript - 修改输入值后,css样式消失

ios - InvalidFirebaseData Swift 3 只能存储 NSNumber、NSString、NSDictionary 和 NSArray 类型的对象。

ios - 如何为 Swift 更新 Firebase 数据?