我想为我的网站生成动态搜索。我正在使用 req.query 在解析查询字符串后获取 JS 对象。我在 foreach 中遇到变量名称价格问题。 网址是: http://www.localhost:3000/listing?price=1&price=2&gender=men&gender=women
var arrayGet = req.query;
var query ={};
for (var k in arrayGet){
if (arrayGet.hasOwnProperty(k)) {
if(k =='gender'){
var gender = arrayGet[k];
query["gender"] = { "$in" : gender };
}else if(k =='colour'){
var colour = arrayGet[k];
query["colour"] = { "$in" : colour };
}else if(k =='price'){
price = arrayGet[k];
if(price.constructor !== Array){
var price = JSON.parse("[" + price + "]");
}
console.log(price);
query.$or = price.forEach(function (currentarray, i) {
console.log('value: '+currentarray[i]);
if(price[i] =='1'){
return {
'price': {'$gte': 0 , '$lte': 100}
}
}else if(price[i] =='2'){
return {
'price': {'$gte': 100 , '$lte': 150}
}
}else if(price[i] =='3'){
return {
'price': {'$gte': 150 , '$lte': 200}
}
}else if(price[i] =='4'){
return {
'price': {'$gte': 200 , '$lte': 1000}
}
}
});
}else if(k =='material'){
var material = arrayGet[k];
query["attributes.caseMaterial"] = { "$in" : material };
}else if(k =='size'){
var size = arrayGet[k];
query["item"] = {$elemMatch: { 'size': { $regex: size, $options: "-i"}, 'stock' : "Available"}};
}else if(k =='options'){
var options = arrayGet[k];
query["attributes.options"] = { "$in" : options };
}
}
}
console.log(query);
Product.find(query, function (err, results) {
console.log(results);
});
错误信息是:
['1','2']
值:1
值:未定义
{ '$or': 未定义,性别:{ '$in': [ '男人', '女人' ] } }
未定义
最佳答案
为什么你会得到{ '$or': undefined, ... }
你正在这样做:
query.$or = price.forEach(...)
但如these docs say, forEach
returns undefined
。所以,这很正常。您应该使用 map
反而。它将返回一个包含两个元素的新数组:
query.$or = price.map(...)
为什么会得到value: undefined
您正在使用 currentarray
参数,但这不是您获得的数组,而是当前价格。因此,在您的示例中,currentarray[1]
等于'2'[1]
,即未定义
。
可能的解决方案
如果这样写,你的代码会更简单:
query.$or = price.map(function (currentPrice) {
switch(currentPrice) {
case '1': return {'price': {'$gte': 0 , '$lte': 100} };
case '2': return {'price': {'$gte': 100 , '$lte': 150} };
case '3': return {'price': {'$gte': 150 , '$lte': 200} };
case '4': return {'price': {'$gte': 200 , '$lte': 1000}};
default : return {};
}
});
关于javascript - Express.js 中的数组 foreach 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46124144/