Gau*_*ar 1 javascript node.js express
我正在Nodejs中创建一个项目并表达我有一个逻辑响应ajax调用查询MongoDb数据库通过其聚合框架,然后处理如此获得的结果.
从MongoDBQuery 获得的结果
[ { _id: 'ALR', count: 7 },
{ _id: 'WTK', count: 3 },
{ _id: 'BWL', count: 9 },
{ _id: 'BAT', count: 9 } ]
Run Code Online (Sandbox Code Playgroud)
此查询的回调函数
, function (err, counts) {
if(err){
console.log(err);
return res.json({status:false, msg : err});
}
if(counts){
console.log(counts);
for (var i = 0; i < counts.length; i++) {
var type = counts[i]._id;
var count = counts[i].count;
if(type == "ALR"){
if(count < 5){
return res.json({status:false, msg : "Minimum 5 All-Rounders"});
}
} else if(type == "BAT"){
if(count < 6){
return res.json({status:false, msg : "Minimum 6 Batsman"});
}
} else if (type == "BWL"){
if(count < 6){
return res.json({status:false, msg : "Minimum 6 Bowlers"});
}
} else if(type == "WTK"){
if(count < 3){
return res.json({status:false, msg : "Minimum 3 Wicket Keepers"});
}
}
}
return res.json({status:true, msg : "Squad Lauched"});
}
});
Run Code Online (Sandbox Code Playgroud)
看起来我在某种If Else地狱,这段代码按预期工作,但我不满意这个,如果有人能至少给出一个以更好的方式做这个回调函数的提示.
你的代码显然非常重复.一种改变方法是创建一个包含必要数据的对象,并根据该方法执行程序逻辑.例如:
var types = {
ALR: { min: 5, name: 'All-Rounders' },
BAT: { min: 5, name: 'Batsman' },
BWL: { min: 4, name: 'Bowlers' },
WTK: { min: 3, name: 'Wicket Keepers' },
};
for (var i = 0; i < counts.length; i++) {
var type = counts[i]._id;
var count = counts[i].count;
if (types[type] && count < types[type].min) {
return res.json({ status: false, msg: 'Minimum ' + types[type].min + ' ' + types[type].name });
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
780 次 |
| 最近记录: |