【问题标题】:Dynamic query to take input from user and do filtering from the database node.js动态查询从用户获取输入并从数据库 node.js 进行过滤
【发布时间】:2020-05-04 16:39:44
【问题描述】:

enter image description here我正在尝试从用户输入的用户那里获取列,好的是正在获取列,而坏的是我应用条件的列不起作用。谁能帮我吗?我想要一个适用于过滤器选项的查询,就像在许多网站中过滤任何产品或其他东西一样。 新手来了!!!

routes.post('/FilterCandidate',function(req,res){
   var fetchparameter={};
   var dynamicquery={author : req.user.username};
   if(req.user.username){
   if(req.body.ConsultantName){
       fetchparameter["ConsultantName"] =  req.body.ConsultantName;
     }
   if(req.body.Location){
      fetchparameter["Location"] =  req.body.Location;
     }
   if(req.body.JobRole){
  fetchparameter["JobRole"] =  req.body.JobRole;
     }
   if(req.body.Skills){
      fetchparameter["Skills"] =  req.body.Skills.split(',');
     }
   if(req.body.VisaStatus){
      fetchparameter["VisaStatus"] =  req.body.VisaStatus;
     } 
   if(req.body.BillingRate){
      fetchparameter["BillingRate"] =  req.body.BillingRate;
     }
   if(req.body.experience){
      fetchparameter["experience"] = req.body.experience;
     }
   if(req.body.jobtype){
      fetchparameter["jobtype"] = req.body.jobtype;
     }
   if(req.body.Availability){
      fetchparameter["Availability"] = req.body.Availability;
    }
   if(req.body.experience){
      fetchparameter["Salary"] = req.body.Salary;
   }
   if(req.body.Salarytype){
      fetchparameter["Salarytype"] = req.body.Salarytype;
   }
    }


 /* This below code for conditions is not working*/

for(var key in fetchparameter){
   if (key== "Salary" ){
     dynamicquery[key] =  {$gte :fetchparameter[key]};
          }
         if(key == "Skills"){
             dynamicquery [key] = {$in : fetchparameter[key]};
          }
         if(key == "experience"){
            dynamicquery[key] = {$gte :fetchparameter[key]};
          }
         else{
             dynamicquery[key] = fetchparameter[key];
             }
   } 
 console.log(dynamicquery);
    Candidate.aggregate([ {$match : dynamicquery }],(err,docs) =>{
       res.render('FilteredCandidate',{'Candidates' : docs});
       });
 });

这是我得到的输出以引用附加图像

【问题讨论】:

  • 请以文本形式输入您的错误消息,以便以后搜索您的问题的其他人可以在 Google 上找到您的问题。

标签: javascript node.js mongodb backend fixed


【解决方案1】:

我认为你应该制作一个匹配对象数组,它会让你的代码更整洁,并希望它能解决你的问题

例如:

var match = {$and:[]};
if(any condition satisfy){
match.$and.push({}) //condition
}

最重要的是检查 match.$and 数组是否为空,如果是则删除 match.$and。此过程将帮助您更好地维护查询并提供更大的灵活性。

【讨论】:

  • 实际上,在检查条件时,条件被视为对象,请参考随附的输出截图。
  • 因为你把它变成了一个键值对,它是类型对象,所以上面的解释将解决你的问题,即使你想让我给出一个合适的例子,我可以将你的查询转换为建议的查询
  • 嘿,如果它对您有用,那么要么将答案标记为已接受,要么编辑问题并在其中添加已解决的标签,这也可能对其他人有所帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-24
相关资源
最近更新 更多