为什么会出现“验证失败”错误?

时间:2020-06-01 11:12:30

标签: node.js express

我有一个基本的expressjs应用程序。当我尝试提出POST请求时,总是出现错误,提示:"User validation failed: name: Path "name" is required., email: Path "email" is required., password: Path "password" is required."

我的请求(json)

[
   {
      "name":"test",
      "email":"test@gmail.com",
      "password":"testtest"
   }
]

控制器:

router.post("/", (req, res) => {
  service.saveUser(req, res);
});

服务(我认为这里应该有问题)

const saveUser = async (req, res) => {
  console.log(req.body);
  const newUser = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  });
  const savedUser = newUser.save();
  res.json(savedUser);
};

最后是User模式:

const Model = db.Schema({
  id: {
    type: Number,
    unique: true,
  },
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
});

1 个答案:

答案 0 :(得分:0)

您请求

[
   {
      "name":"test",
      "email":"test@gmail.com",
      "password":"testtest"
   }
]

但是您应该请求

{
   "name":"test",
   "email":"test@gmail.com",
   "password":"testtest"
}