[英]How do I build a dynamic query in Mongoose?
我需要使用以下示例數據構建查詢:
{
brandFilters:[ { brand: 'Amana', checked: true },
{ brand: 'Whirlpool', checked: true } ],
priceFilters:[ { low: 100, high: 200, label: '$100 - $200', checked: true },
{ low: 200, high: 300, label: '$200 - $300', checked: true } ],
rating: null }
查詢的第一部分構建品牌條件,如下所示;
let brands = [];
let productQuery = Product.find();
if(filters.brandFilters.length) {
for(let filter of filters.brandFilters) {
brands.push(filter.brand)
}
productQuery.where('brand').in(brands)
console.log('brands', brands)
}
第二部分應該構建價格標准,如下所示:
if(filters.priceFilters.length) {
for(let filter of filters.priceFilters) {
productQuery.where('price').gte(+filter.low).lte(+filter.high);
}
}
目的是為每個價格過濾器添加一個“where”子句,如上面的數據所示。 問題是多個 where 沒有添加價格標准的條款。 for 循環中的每個連續價格過濾器都會覆蓋最后一個。 因此,我的價格過濾器沒有多個“where”子句,查詢只包含一個 for 循環的最后一次迭代。
我正在嘗試進行如下查詢:
productQuery.where('brand').in(['Amana', 'Whirlpool'])
productQuery.where('price').gte(100).lte(200)
productQuery.where('price').gte(200).lte(300)
因此,您嘗試構建的查詢應如下所示:
{
"$and":[
{"$or":[
{"price":{"$gte":100,"$lte":200}},
{"price":{"$gte":200,"$lte":300}}
]
},
{"brand":{"$in":["Amana","Whirlpool"]}}
]
}
所以它包含$or
以包含多個價格范圍。 為此,您可以將該查詢構建為純 JavaScript 對象,然后將其傳遞給find
方法,請嘗試:
let query = {
'$and': []
};
var priceQuery = [];
let brands = [];
if(filters.priceFilters.length) {
for(let filter of filters.priceFilters) {
priceQuery.push({ 'price': { $gte: +filter.low, $lte: +filter.high } });
}
query['$and'].push({ '$or': priceQuery });
};
if(filters.brandFilters.length) {
for(let filter of filters.brandFilters) {
brands.push(filter.brand)
}
query['$and'].push({ 'brand': { '$in': brands } });
}
進而
let products = await Product.find(query);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.