【问题标题】:(node:1572) UnhandledPromiseRejectionWarning: ValidationError: profile validation failed: education.0.fieldsofstudy: Path `fieldsofstudy` is required(节点:1572)UnhandledPromiseRejectionWarning:ValidationError:配置文件验证失败:education.0.fieldsofstudy:需要路径“fieldsofstudy”
【发布时间】:2018-12-12 12:37:03
【问题描述】:

我正在尝试查找此验证错误的根本原因:(node:1572) UnhandledPromiseRejectionWarning: ValidationError: profile validation failed: education.0.fieldsofstudy: Path fieldsofstudy is required.
即使我将“fieldsofstudy”更改为其他名称,例如“majors”,这种情况也会发生。仍然会返回相同的错误消息。

这是我的教育资料代码

// @route   POST api/profile/education
// @desc    Add education to profile
// @access  Private
router.post(
"/education",
passport.authenticate("jwt", { session: false }),
(req, res) => {
const { errors, isValid } = validateEducationInput(req.body);

// Check Validation
if (!isValid) {
  // Return any errors with 400 status
  return res.status(400).json(errors);
}

Profile.findOne({ user: req.user.id }).then(profile => {
  const newEdu = {
    school: req.body.school,
    degree: req.body.degree,
    fieldofstudy: req.body.fieldofstudy,
    from: req.body.from,
    to: req.body.to,
    current: req.body.current,
    description: req.body.description
  };

  // Add to exp array
  profile.education.unshift(newEdu);

  profile.save().then(profile => res.json(profile));
  });
 }
);

这是我的教育标签代码

data.school = !isEmpty(data.school) ? data.school : "";
data.degree = !isEmpty(data.degree) ? data.degree : "";
data.fieldofstudy = !isEmpty(data.fieldofstudy) ? data.fieldofstudy:"";
data.from = !isEmpty(data.from) ? data.from : "";

if (Validator.isEmpty(data.school)) {
  errors.school = "School field is required";
 }

if (Validator.isEmpty(data.degree)) {
    errors.degree = "Degree field is required";
 }

if (Validator.isEmpty(data.fieldofstudy)) {
   errors.fieldofstudy = "Field of study field is required";
 }

 if (Validator.isEmpty(data.from)) {
   errors.from = "From date field is required";
 }

 return {
   errors,
  isValid: isEmpty(errors)
 };
};

【问题讨论】:

  • 数据。 fieldofstudy 是我的 const newEdu 的一部分,即使我将变量切换到 data.majors,我仍然收到相同的错误消息。
  • 这个问题在我重新启动机器并重新配置依赖项后得到解决。

标签: javascript node.js mongodb mongoose


【解决方案1】:

问题出在您的模型中。当您在模型文件夹中创建配置文件架构时,您不小心将其命名为 fieldsofstudy 而不是 fieldofstudy(单数)。验证中的字段必须与模型中的字段匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-18
    • 2020-11-26
    • 2020-06-10
    • 2020-08-20
    • 2022-12-14
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多