如何验证在Express中未未定义参数数据

时间:2019-05-01 17:32:46

标签: node.js express

我正在使用Nodejs和Express。为了更新数据,我有以下代码

exports.update = (req, res) => {  
  const updatedUser = {
    username: req.body.username,
    age: req.body.age,
    dateOfBirth: req.body.dateOfBirth,
    occupation: req.body.occupation,
    businessName: req.body.businessName,
    joinDate: req.body.joinDate,
    familyMembers: req.body.familyMembers,
    isActiveMembership: req.body.isActiveMembership,
    membershipEnd: req.body.membershipEnd
  };

  User.findByIdAndUpdate(req.body._id,updatedUser);
};

问题是,如果用户未传递任何参数,则undefined将被添加到数据库中。我显然不想单独检查每个参数(如果未定义)。

那么,什么是处理此问题的好方法?

2 个答案:

答案 0 :(得分:0)

遍历req.body中的可用属性,并设置要相应更新的属性和值:

const updatedUser = Object.keys(req.body).map(el => {
  return { [el]: req.body[el] }
})

const req = {
  body: {
    age: 2,
    name: 'hey',
    occupation: 'troll'
  }
}

const updatedUser = Object.keys(req.body).map(el => {
  return { [el]: req.body[el] }
});
console.log(updatedUser)
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

所以目前我正在使用以下方法。

exports.update = (req, res) => {  
  const updatedUser = {
    username: req.body.username,
    age: req.body.age,
    dateOfBirth: req.body.dateOfBirth,
    occupation: req.body.occupation,
    businessName: req.body.businessName,
    joinDate: req.body.joinDate,
    familyMembers: req.body.familyMembers,
    isActiveMembership: req.body.isActiveMembership,
    membershipEnd: req.body.membershipEnd
  };

  const filteredValue = _.pickBy(updatedUser,function(item){
    return item !== undefined;
  })

  //Save the filteredValue in the DB

};

*如果有人建议使用更好的方法,则将使问题一直存在。