猫鼬验证错误:第一个:路径“ first”是必需的,最后一个:路径“ last`是必需的。”

时间:2020-04-03 21:28:37

标签: javascript node.js mongodb express mongoose

因此,关于此还有另一篇文章,但似乎根本没有帮助。我正在使用Mongoose创建一个MongoDB网站来存储名称。这是我的路线和型号代码:

const router = require("express").Router();
const Name = require("../models/name.model");
const moment = require("moment");

router.route("/").get((req, res) => {
  Name.find()
    .then((names) => res.json(names))
    .catch((err) => res.status(400).json("Error: " + err));
});
router.route("/add").post((req, res) => {
  const newName = new Name({
    first: req.body.firstName,
    last: req.body.lastName,
    date: moment().format("yyyy-mm-dd:hh:mm:ss"),
  });
  newName
    .save()
    .then(() => res.json("Name added to the list!"))
    .catch((err) => res.status(400).json("Error: " + err));
});

router.route("/:id").get((req, res) => {
  Name.findByIdAndDelete(req.params.id)
    .then(() => res.json("Name was deleted from the list!"))
    .catch((err) => res.status(400).json("Error: " + err));
});

module.exports = router;
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const nameSchema = new Schema({
  first: { type: String, required: true },
  last: { type: String, required: true },
  date: { type: String },
});

module.exports = mongoose.model("Name", nameSchema);

每当我尝试发出POST请求(失眠)时,都会发送

{
    "first": "Bob",
    "last": "Pelicano"
}

我收到此错误: “错误:ValidationError:第一:路径first是必需的。最后:路径last是必需的。”

1 个答案:

答案 0 :(得分:2)

您缺少body-parser

通过运行"body-parser"安装npm install --save body-parser,并在任何post/get/put/delete处理程序之前添加到您的代码中:

router.use(bodyParser.json());

别忘了include/require body-parser,在文件顶部添加:

const bodyParser = require("body-parser");

而且,别忘了在失眠时设置正确的标题(content-type: application/json)