我本质上是试图构建一个产品过滤器,用户可以从任何过滤器选项中选择(或不选择(例如,不需要它们)。
我的Firestore设置为:
product
{
colour: "white"
brand: "a brand"
}
目前,我可以使用此代码过滤说出的'颜色':
filterProducts(value: string){
this.filteredProducts = this.db.collection('products', ref => ref.where('colour', '==', value)).valueChanges();
}
我如何调整以上内容以能够对颜色,品牌或两者进行过滤?这有可能吗?
[如果您询问是否可以在多个字段上查询,答案为“是”。例如,过滤品牌和颜色:
ref.where('colour', '==', 'white').where('brand', '==', 'a brand')
有关此内容的更多信息,请参阅filtering data和compound queries上的Firebase文档。
当然,您需要将两个值都传递到filterProducts
方法中才能使用它们。
如果您只想在用户为该过滤器指定值时添加条件,则可以执行以下操作:
ref = firebase.firestore.collection(...); // whatever you already have
if (colourValue) {
ref = ref.where('colour', '==', colourValue);
}
if (brandValue) {
ref = ref.where('brand', '==', brandValue);
}