即使提供数据,为什么仍收到验证错误?

时间:2019-05-25 19:59:43

标签: javascript mongodb validation mongoose postman

由于某种原因,我的应用后端认为我在测试路线时并没有提供数据。

我环顾四周,但是没有找到与我遇到的问题完全匹配的东西。

我一直在按照以下教程系列尝试为我的应用构建后端:https://www.youtube.com/playlist?list=PL55RiY5tL51q4D-B63KBnygU6opNPFk_q

在向模型添加验证之前,我的HTTP请求收到200和201。添加验证后,我开始收到错误消息,通知我即使我在也没有提供必要的信息。

我正在使用Mongoose 5.5.8,Cors 2.8.5,Body-Parser 1.19.0和Postman 7.1.1。

我曾经尝试使用.exec()方法,但这只会给我带来更严重的错误。

这是我的模特:

const studentSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  first_name: { type: String, required: true },
  last_name: { type: String, required: true },
  preferred_name: { type: String, required: true }
});

module.exports = mongoose.model("Student", studentSchema);

这是我的控制人:

  add_student: (req, res) => {
    const student = new Student({
      _id: new mongoose.Types.ObjectId(),
      first_name: req.body.first_name,
      last_name: req.body.last_name,
      preferred_name: req.body.preferred_name
    });
    student
      .save()
      .then(result => {
        console.log(result);
        res.status(201).json({
          message: "Student added!",
          createdStudent: {
            first_name: result.first_name,
            last_name: result.last_name,
            preferred_name: result.preferred_name
          }
        });
      })
      .catch(err => {
        console.log(err);
        res.status(422).json({
          error: err
        });
      });
  },

这是我的路线:

router.route("/")
  .post(studentController.add_student)

这是我要通过邮递员传递的数据:

{
"first_name": "Steve",
"last_name": "Jones",
"preferred_name": "Stevie Boy"
}

如您所见,我正在传递数据,但是我不断收到错误消息,好像根本没有信息一样。

我想我需要知道如何正确地通过控制器提供传递数据,所以我的应用程序认为我没有试图传递空对象。

1 个答案:

答案 0 :(得分:0)

我遇到的问题是用户(我)错误。在邮递员中,Screen grab of my Postman GUI

在它说JSON(application / json)的地方,我说它是文本。将其设置为JSON可解决我的问题。

毫无疑问,我对此感到很愚蠢!

相关问题