[英]Dynamic query to take input from user and do filtering from the database node.js
在此处输入图像描述我正在尝试的是从用户输入的用户那里获取列,好处是正在获取列,而坏处是我应用条件的列不起作用。谁能帮帮我? 我想要一个适用于过滤器选项的查询,就像在许多网站中过滤任何产品或东西一样。 新手来啦!!!
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});
});
});
这就是我得到的 output 以参考附图
我认为你应该匹配 object 数组它会让你的代码更整洁,并希望它能解决你的问题
前任:
var match = {$and:[]};
if(any condition satisfy){
match.$and.push({}) //condition
}
最重要的是检查 match.$and 是否为空,如果它是然后删除 match.$and。 此过程将帮助您更好地维护您的查询提供更大的灵活性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.