【问题标题】:Dynamic Query MongoDB动态查询 MongoDB
【发布时间】: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


【解决方案1】:

您的查询的问题是您试图构建一个字符串而不是直接构建一个对象,例如 mongoDB 和 mongoose 接受:

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/

这是一个你可以玩的jsbin

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

【讨论】:

  • 非常感谢。卡在这个问题上一段时间了。
【解决方案2】:

我听从了 Derek 的建议,就如何动态构建查询条件而言,这是非常正确的。但似乎此代码无法处理未指定搜索参数的情况。

具体来说,如果所有 req.body 参数都是空的,那么您有一个带有空 $and 数组的查询对象,如下所示:

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);
        }
});

Derek,如果我说错了,请见谅,不想指出错误的问题。

【讨论】:

  • 嗨 Vikas,感谢您为 Derek 回答添加了额外的步骤。这对我的场景很有效。
  • 结合Derek的逻辑,这解决了我的问题。谢谢。
猜你喜欢
  • 1970-01-01
  • 2015-04-09
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多