动态查询MongoDB

时间:2016-10-11 21:00:51

标签: node.js mongodb express mongoose

我尝试根据从客户端搜索表单接收的数据构建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 $查询?

2 个答案:

答案 0 :(得分:8)

您的查询问题是您正在尝试构建字符串而不是直接构建对象,例如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(",") }});
  }

你可以看到,而不是推入一个字符串,而是推入符合文档规范的直接对象。

有关详细信息,请参阅此处的文档:

  1. https://docs.mongodb.com/manual/reference/operator/query/and/
  2. https://docs.mongodb.com/manual/reference/operator/query/in/
  3. 这是一个可以玩的jsbin

    1. http://jsbin.com/cequbipiso/edit?js,console

答案 1 :(得分:2)

我遵循了Derek的建议,即如何动态构建查询条件。但似乎此代码不处理未指定搜索参数的情况。

具体来说,如果所有req.body参数都为空,那么你有一个查询对象,其中$和数组为空,如下所示:

q['$and']=[];

这会导致MongoError: $and/$or/$nor must be a nonempty array错误。

以下是我为解决此问题所采取的措施:

var conditions = {}; //declare a conditions object
var and_clauses = []; //an array for the and conditions (and one for or conditions and so on)

if((!!req.body.email_id)){
    and_clauses.push({ 'email_id': {$regex: req.body.email_id }});
}   

if(and_clauses.length > 0){ 
    conditions['$and'] = and_clauses; // filter the search by any criteria given by the user
}

//Run the query
User.find(conditions,
    function(err, users) {
        if (err){
            console.log(err);
            res.status(500).send(err);
        }else{
            console.log(users);
            res.status(200).json(users);
        }
});

德里克,如果我出错了,请道歉,不要错误地指出问题。