Run*_*olk 5 mongoose mongodb node.js express
我正在尝试基于从客户端搜索表单接收的数据构建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(",") + '}}');
}
Run Code Online (Sandbox Code Playgroud)
但结果对象是:
{ '$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}}' ] }
Run Code Online (Sandbox Code Playgroud)
如何从req.body对象中正确构建MongoDB $ in查询?
您的查询的问题是您正在尝试构建字符串而不是直接构建对象,如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(",") }});
}
Run Code Online (Sandbox Code Playgroud)
您可以看到,而不是推入字符串,而是推入符合文档规范的直接对象.
有关更多信息,请参阅此处的文档:
这是一个jsbin你可以玩的工作:
我遵循了 Derek 的建议,该建议在如何动态构建查询条件方面很重要。但似乎此代码无法处理未指定搜索参数的情况。
具体来说,如果所有 req.body 参数都为空,那么您就有一个带有空 $and 数组的查询对象,如下声明:
q['$and']=[];
Run Code Online (Sandbox Code Playgroud)
这会导致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);
}
});
Run Code Online (Sandbox Code Playgroud)
德里克,如果我做错了什么,我很抱歉,不想错误地指出问题。
| 归档时间: |
|
| 查看次数: |
5785 次 |
| 最近记录: |