2017-09-08 52 views
0

我想为我的网站生成动态搜索。在解析查询字符串后,我正在使用req.query获取JS对象。我在变量名称价格的foreach中遇到了问题。 链接: http://www.localhost:3000/listing?price=1&price=2&gender=men&gender=women在express.js中的数组foreach错误

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

值:未定义

{ '$或':未定义,性别:{'$ in':['men','women']}}

未定义

+0

你在使用的前端? – yBrodsky

回答

2

为什么你{ '$or': undefined, ... }

你这样做:

query.$or = price.forEach(...) 

但作为these docs say, forEach returns undefined。所以,这很正常。您应该改用map。它会返回一个新的数组元素都:

query.$or = price.map(...) 

为什么你value: undefined

您使用的是currentarray参数,但是这不是你的阵列,它目前的价格。因此,在您的示例中,currentarray[1]等于'2'[1],即undefined

可能的解决方法

如果这样写您的代码会更简单:

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 {}; 
    } 
});