dynamic查询MongoDB
我试图build立一个基于从客户端search表单收到的数据的MongoDB查询对象。 我的目标是用用户提供的任何和所有标准来查询数据库,同时允许用户如果他们select留下一些search字段空白。
这是我目前在查询对象的尝试是:
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对象的查询中构build一个MongoDB $?
你的查询的问题是你正在尝试构build一个string,而不是直接构build一个对象,如mongoDB&mongoose accept:
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(",") }}); }
你可以看到,不是推入一个string,而是推入一个符合文档规范的直接对象。
有关更多信息,请参阅此处的文档:
- https://docs.mongodb.com/manual/reference/operator/query/and/
- https://docs.mongodb.com/manual/reference/operator/query/in/
这里有一个你可以玩的工作jsbin
:
我遵循了Derek的build议,关于如何dynamic地构build查询条件, 但是看起来这个代码并不处理没有指定search参数的场景。
特别是,如果所有的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); } });
德里克,道歉,如果我有什么问题,不想错误地指出一个问题。