ren*_*dom 12 javascript firebase google-cloud-firestore
例如,我的书籍列表中有动态过滤器,我可以设置特定的颜色,作者和类别.此过滤器可以一次设置多种颜色和多个类别.
Book > Red, Blue > Adventure, Detective.
Run Code Online (Sandbox Code Playgroud)
如何有条件地添加"where"?
firebase
.firestore()
.collection("book")
.where("category", "==", )
.where("color", "==", )
.where("author", "==", )
.orderBy("date")
.get()
.then(querySnapshot => {...
Run Code Online (Sandbox Code Playgroud)
Dou*_*son 33
正如您在API文档中看到的那样,collection()方法返回一个CollectionReference.CollectionReference扩展了Query. Query.where()和Query.orderBy()也返回Query对象.所以你可以像这样重写你的代码:
var query = firebase.firestore().collection("book")
query = query.where(...)
query = query.where(...)
query = query.where(...)
query = query.orderBy(...)
query.get().then(...)
Run Code Online (Sandbox Code Playgroud)
现在,您可以输入条件来确定要在每个阶段应用哪些过滤器.
dan*_*y74 31
Firebase 版本 9
文档没有涵盖这一点,但以下是如何向查询添加条件 where 子句:
import { collection, query, where } from 'firebase/firestore'
const queryConstraints = []
if (group != null) queryConstraints.push(where('group', '==', group))
if (pro != null) queryConstraints.push(where('pro', '==', pro))
const q = query(collection(db, 'videos'), ...queryConstraints)
Run Code Online (Sandbox Code Playgroud)
这个答案的来源是一些直观的猜测。
小智 17
您可以使用多个 where 子句过滤数据:
import { query, collection, where, getDocs } from "firebase/firestore";
const q = query(
collection(db, "products"),
where("category", "==", "Computer"),
where("types", "array-contains", ['Laptop', 'Lenovo', 'Intel']),
where("price", "<=", 1000),
);
const docsSnap = await getDocs(q);
docsSnap.forEach((doc) => {
console.log(doc.data());
});
Run Code Online (Sandbox Code Playgroud)
除了@Doug Stevenson 的回答。当您拥有多个时,有where必要使其更具活力,就像我的情况一样。
function readDocuments(collection, options = {}) {
let {where, orderBy, limit} = options;
let query = firebase.firestore().collection(collection);
if (where) {
if (where[0] instanceof Array) {
// It's an array of array
for (let w of where) {
query = query.where(...w);
}
} else {
query = query.where(...where);
}
}
if (orderBy) {
query = query.orderBy(...orderBy);
}
if (limit) {
query = query.limit(limit);
}
return query
.get()
.then()
.catch()
}
// Usage
// Multiple where
let options = {where: [["category", "==", "someCategory"], ["color", "==", "red"], ["author", "==", "Sam"]], orderBy: ["date", "desc"]};
//OR
// A single where
let options = {where: ["category", "==", "someCategory"]};
let documents = readDocuments("books", options);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8554 次 |
| 最近记录: |