firebase - 基于参数的具有多个 where 子句的 Firestore 查询
问题描述
我想根据传入的参数查询具有多个 where 子句的 Firestore 数据库。以下代码块有效:
getProducts2(accountId: string, manufacturer?: string, materialType?: string): Promise<Product[]> {
return new Promise<Product[]>((resolve, reject) => {
const productCollection2: AngularFirestoreCollection<FreightRule> = this.afs.collection('products');
const query = productCollection2.ref
.where('materialType', '==', materialType)
.where('manufacturer', '==', manufacturer);
query.get().then(querySnapshot => {
if (querySnapshot.size > 0) {
const data = querySnapshot.docs.map(documentSnapshot => {
return documentSnapshot.data();
}) as Product[];
resolve(data);
} //todo else...
});
});
}
但我真正想做的是有条件地包含基于可选参数的 where 子句。以下是我想要的,但它不起作用:
getProducts2(accountId: string, manufacturer?: string, materialType?: string): Promise<Product[]> {
return new Promise<Product[]>((resolve, reject) => {
const productCollection2: AngularFirestoreCollection<FreightRule> = this.afs.collection('products');
const query = productCollection2.ref;
if (manufacturer) {
query.where('manufacturer', '==', manufacturer);
}
if (materialType) {
query.where('materialType', '==', materialType);
}
query.get().then(querySnapshot => {
if (querySnapshot.size > 0) {
const data = querySnapshot.docs.map(documentSnapshot => {
return documentSnapshot.data();
}) as Product[];
resolve(data);
} //todo else...
});
});
}
虽然有效,但此代码仅返回所有没有过滤的产品。
有没有办法构造它,以便我可以根据可选参数进行过滤?
编辑:我意识到我可以做类似的事情:
let query;
if (manufacturer && materialType) {
query = productCollection2.ref.where(....).where(....)
} else if (manufacturer) {
query = productCollection2.ref.where(....)
} else if (materialType) {
query = productCollection2.ref.where(....)
}
我只是希望有一些更优雅的东西。
解决方案
建立在先前的查询之上,不要重复先前的查询:
let query = collection // initial query, no filters
if (condition1) {
// add a filter for condition1
query = query.where(...)
}
if (condition2) {
// add a filter for condition2
query = query.where(...)
}
// etc
推荐阅读
- php - 如何从 Collection 创建一个 Laravel Eloquent 模型?
- .net - Autofac 替换 MEF Extensions 通过目录地址获取服务列表
- laravel - 每当弹性 beanstalk 上的新版本发布时,Laravel 用户都会注销
- javascript - 使用 Apps 脚本在两个 Google 表格中突出显示并查找匹配单元格的位置(行和列)
- spring - 春季微软团队会议邀请(推送通知)
- google-api - 更新 Google People API 中的联系人
- autocomplete - 在松弛工作流上自动填充
- javascript - 无法通过以下方式找到元素:[data-testid=“movieList”]
- react-native - (反应原生)如何使用地理定位将地图视图集中在用户身上
- c - 我可以或应该制作布尔位字段吗?