javascript - 动态查询从用户获取输入并从数据库 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});
});
});
这就是我得到的输出以引用所附图像
解决方案
我认为您应该制作一个匹配对象数组,它会使您的代码更加整洁,并希望它能解决您的问题
前任:
var match = {$and:[]};
if(any condition satisfy){
match.$and.push({}) //condition
}
最重要的是检查 match.$and 是否为空,如果它是然后删除 match.$and。此过程将帮助您更好地维护您的查询提供更大的灵活性。
推荐阅读
- windows - 没有从 FormIO createForm() API 获得回调
- python - Tabula-py 不读取文件的全部数据
- java - “类型不匹配:无法从 double 转换为 int 错误”
- database - Flutter roodBundle.load() 未加载更新的资产
- angular - 通过 url 输入输入时,Angular 应用程序未正确引导
- python-3.x - Python中的最小距离算法
- android - 有没有办法获取安装应用程序的链接?
- c++ - CMake 错误:在构建 docker 映像时,源目录“/”似乎不包含 CMakeLists.txt
- c - 如何在来自 clang 或 clang-tidy 的简单返回语句中获取隐式转换为 bool 的警告
- sql - 一次又一次地重复设置的n条记录,直到它到达最后