嗨,我自学了MEAN堆栈,并且有一个关于如何减少在我的代码中检查数量的问题。如何减少if语句的数量
基本上这个工作由用户填写他/她的设置页面,然后点击输入我们然后发送数据到服务器,所以我们可以更新mongo。
我似乎得到这个工作,让用户编辑某些领域,而不是所有的唯一方法是确保发送到服务器的数据不等于空,但肯定必须有一个更好的方法然后通过为每个字段运行if语句。
有问题的代码是这样
//user.username = req.body.username;
if (age != null) {
user.age = age;
}
if (bio != null) {
user.bio = bio;
}
if (location != null) {
user.location = location;
}
if (team != null) {
user.team = team;
}
if (tags != null) {
user.tags = tags;
}
if (email != null) {
user.email = email;
}
客户端代码
$scope.savesettings = function(provider){
var theUser = JSON.parse(localStorage.getItem("User-Data"));
var user = theUser["_id"];
var request = {};
var request = {
user: user,
username: $scope.settings_username,
email: $scope.settings_email,
age: $scope.settings_age,
location: $scope.settings_location,
team: $scope.settings_team,
bio:$scope.settings_bio,
profilebanner: $scope.settings_profilebanner,
avatar: $scope.settings_avatar
};
console.log(request);
//send to server
$http.put('api/social/updatesettings', request).success(function(response){
alertify.success("Your settings have been successfully saved.");
localStorage.clear();
localStorage.setItem('User-Data', JSON.stringify(response));
}).error(function(error){
alertify.error("Hmmm an issue has occured.");
});
};
服务器代码
var User = require('../../datasets/userModel');
module.exports.updatesettings =函数(REQ,RES){
var age = req.body.age;
var bio = req.body.bio;
var location = req.body.location;
var team = req.body.team;
var tags = req.body.tags;
var email = req.body.email;
var profilebanner = req.body.profilebanner;
var avatar = req.body.avatar;
User.findOne({_id: req.body.user}, function (err, user){
//user.username = req.body.username;
if (age != null) {
user.age = age;
}
if (bio != null) {
user.bio = bio;
}
if (location != null) {
user.location = location;
}
if (team != null) {
user.team = team;
}
if (tags != null) {
user.tags = tags;
}
if (email != null) {
user.email = email;
}
user.save(function(err){
if (err){
console.log(err);
res.status(500).send();
//res.json(user);
} else {
console.log("success");
res.json(user);
}
})
});
};
你从哪里分配变量?例如,'if(age!= null)','age'从哪里来? – chridam
你是否考虑过包装数组中的所有字段,然后在其上运行forEach()方法,这将导致代码更少,因为你只有1条语句。 –
会将它添加到现在的队友 –