我想在mongoose中创建动态搜索(获取请求中的URL)。
以下是我的网址示例 http://www.localhost:3000/listing?&colour=blue&gender=women
用户可以选择多种颜色和性别,以便网址可以 http://www.localhost:3000/listing?&colour=blue&gender=women&colour=red&gender=men
我的mongodb中有3条查询记录,其中包含
等数据1)性别:'男性', 颜色:'红色'
2)性别:'女', 颜色:'蓝色'
3)性别:'女性', 颜色:'蓝色'
var productSchema = new Schema ({
price: String,
gender: String,
colour: String,
item: [{
name: String,
slug: String,
sku: String,
size : String,
stock: String,
}],
attributes: {
waterProof : String,
warranty : String,
caseMaterial : String,
movement : String,
lens : String,
bandMaterial : String,
options : String,
typeOfMovement : String,
}
});
var arrayGet = req.query;
var generateQuery ="{";
for (var k in arrayGet){
if (arrayGet.hasOwnProperty(k)) {
if(k =='gender'){
var gender = arrayGet[k];
}else if(k =='colour'){
var colour = arrayGet[k];
}
}
if (typeof gender !== 'undefined'){
generateQuery += '{gender : { $in: gender },';
}
if (typeof colour !== 'undefined') {
generateQuery += '{price : { $in: colour }';
}
generateQuery +="}";
// i get 3 query from mongoDB which is wrong
Product.find(generateQuery, function(err, result) {
console.log(result);
})
//i get 2 query from mongoDB which is correct
Product.find({gender : { $in: gender },colour : { $in: colour }},function(err,result){
console.log(result);
})
我可以知道我做错了吗
答案 0 :(得分:0)
为什么不使用$或运算符将所有查询合并为一个?
Product.find({
$or [
{ colour: 'blue', gender: 'women' },
{ colour: 'red', gender: 'men' }
]
}, function (err, results) {
});
以http://www.localhost:3000/listing?&colour=blue&gender=women&colour=red&gender=men为例,您的req.query
应该是
{
colour: [
'blue',
'red'
],
gender: [
'women',
'men'
]
}
我假设颜色和性别数组的长度是相同的,所以你可以做
var query = {};
query.$or = req.query.colour.map(function (colour, i) {
return {
colour: colour,
gender: req.query.gender[i]
}
});
然后再做
Product.find(query, function (err, results) {
});