2017-09-08 17 views
0

mongooseから動的検索を作成したい(リクエストでURLを取得する)。ここでmongooseで動的検索を作成する方法

は、URLが http://www.localhost:3000/listing?&colour=blue&gender=women&colour=red&gender=men

が好きなことができるように、複数の色や性別を選択することができ、私のURLのサンプル http://www.localhost:3000/listing?&colour=blue&gender=women

ユーザーである私は

などのデータと私のMongoDBの3クエリーのレコードを持っています

1)性別:「男性」 色:「赤」

2)性別:「women」、 色: '青'

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 generateQeury ="{"; 
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'){ 
    generateQeury += '{gender : { $in: gender },'; 
} 
if (typeof colour !== 'undefined'){ 
    generateQeury += '{price : { $in: colour }'; 
} 

generateQeury +="}"; 

// i get 3 query from mongoDB which is wrong 
Product.find(generateQeury,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

使用して一つにすべてのクエリをマージしないのはなぜ$か演算子?例としてhttp://www.localhost:3000/listing?&colour=blue&gender=women&colour=red&gender=menを使用して

Product.find({ 
    $or [ 
     { colour: 'blue', gender: 'women' }, 
     { colour: 'red', gender: 'men' } 
    ] 
}, function (err, results) { 

}); 

、あなたの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) { 

}); 
を行います
関連する問題