2017-09-08 51 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 {}; 
    } 
});