Mongoose validation error: first: Path `first` is required., last: Path `last` is required."

So there is another post on this, but it didn't seem to help at all. I am making a MongoDB website to store names, using mongoose. Here is my route and model code:

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);

Whenever I try to make a POST request(with insomnia), sending

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

I get this error: "Error: ValidationError: first: Path first is required., last: Path last is required."

Upvotes: 0

Views: 190

Answers (1)

Marc
Marc

Reputation: 3924

You are missing a body-parser.

Install "body-parser" by running npm install --save body-parser and add to your code before any post/get/put/delete handler:

router.use(bodyParser.json());

Dont forget to include/require the body-parser, add on top of your file:

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

And also, don't forget to set the right headers (content-type: application/json) in insomnia.

Upvotes: 2

Related Questions