Reputation: 87
I want to generate dynamic search for my website. I am using req.query to get JS object after the query string is parsed. I was facing problem in foreach in variable name price. Url is : 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);
});
The error message is:
[ '1', '2' ]
value: 1
value: undefined
{ '$or': undefined, gender: { '$in': [ 'men', 'women' ] } }
undefined
Upvotes: 0
Views: 415
Reputation: 25659
Why you get { '$or': undefined, ... }
You are doing this:
query.$or = price.forEach(...)
But as these docs say, forEach
returns undefined
. So, it's normal. You should use map
instead. It will return a new array with both elements:
query.$or = price.map(...)
Why you get value: undefined
You are using a currentarray
parameter, but that's not an array you get, it's the current price. So, in your example, currentarray[1]
is equal to '2'[1]
, which is undefined
.
Possible solution
Your code would be simpler if written like this:
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 {};
}
});
Upvotes: 2