【发布时间】:2017-02-20 13:11:07
【问题描述】:
我正在尝试根据从客户端搜索表单接收到的数据构建 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 $in 查询?
【问题讨论】:
-
我有,但我找不到任何有关动态构建查询对象的有用信息。
-
请务必在下方查看我的回答,如果符合您的需求,请标记为正确
-
它超出了我的需求!感谢您提供如此完整而完整的答案。
-
没问题!很高兴我能帮上忙!
标签: node.js mongodb express mongoose