クライアント側の検索フォームから受け取ったデータに基づいてMongoDBクエリオブジェクトを作成しようとしています。私の目標は、ユーザーが提供するすべての条件でデータベースを照会することですが、ユーザーが選択すると検索フィールドを空白のままにすることができます。動的クエリMongoDB
var q = {}; // declare the query object
q['$and']=[]; // filter the search by any criteria given by the user
if((req.body.learninglanguages).length > 0){ // if the criteria has a value or values
q["$and"].push('{learningLanguages: {$in: ' + req.body.learninglanguages.split(",") + '}}'); // add to the query object
}
if((req.body.spokenlanguages).length > 0){
q["$and"].push('{spokenLanguages: {$in: ' + req.body.spokenlanguages.split(",") + '}}');
}
if((req.body.country).length > 0){
q["$and"].push('{country: {$in: ' + req.body.country.split(",") + '}}');
}
if((req.body.commethod).length > 0){
q["$and"].push('{comMethod: {$in: ' + req.body.commethod.split(",") + '}}');
}
しかし、結果のオブジェクトは、次のとおりです:
これは、クエリオブジェクトでの私の現在の試みはあるさ
{ '$and':
[ '{learningLanguages: {$in: Albanian,American Sign Language,Amharic,Arabic,Arabic (Egyptian)}}',
'{spokenLanguages: {$in: Akan,Albanian,American Sign Language,Amharic}}',
'{country: {$in: Åland Islands}}',
'{comMethod: {$in: whatsapp,email,face to face,skype}}' ] }
私が正しくreq.bodyオブジェクトからのクエリでMongoDBの$を構築することができますどのように?
ドキュメントを参照しましたか? – Derek
私は持っていますが、クエリオブジェクトを動的に構築するのに役立つものは何も見つかりません。 –
下記の私の答えをチェックし、それがあなたのニーズを満たしている場合はそれを正しくマークしてください – Derek