【问题标题】:Why am I getting a validation error even though I'm providing data?为什么即使我提供了数据,我也会收到验证错误?
【发布时间】:2019-10-11 23:29:30
【问题描述】:

由于某种原因,我的应用程序的后端在测试我的路线时不认为我在提供数据,即使我在提供数据。

我环顾四周,但没有发现任何与我遇到的问题完全匹配的东西。

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

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

我正在使用 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)

这是我试图通过 Postman 传递的数据:

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

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

我想我需要知道如何通过我的控制器正确地提供传递数据,所以我的应用不会认为我在尝试传递一个空对象。

【问题讨论】:

  • 您遇到的错误是什么?另外,为什么要处理_id mongoDb 会自动为您创建一个。不需要在您的架构中定义_id
  • 我得到的错误是 422(不可处理的实体)我已经硬编码到我的控制器中。 (当我尝试使用 .exec() 方法时,它抛出了 500)我定义了 _id,因为这就是我一直在关注的教程中的那个人所做的。这是一个购物车应用程序,在数据库中有多个连接的文档,我认为这就是我需要做的。

标签: javascript mongodb validation mongoose postman


【解决方案1】:

我遇到的问题是用户(我)错误。在邮递员中,

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

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

【讨论】:

    猜你喜欢
    • 2022-11-03
    • 2021-08-21
    • 2023-03-29
    • 2022-06-12
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多