rmc3
rmc3

Reputation: 129

Mongoose ValidationError: validation failed: Path is required

I am getting an error when I enter information in the ejs form on my web application pertaining to my mongoDB schema:

The error im getting:

ValidationError: Subscriber validation failed: grade1: Path `grade1` is required., grade2: Path `grade2` is required., grade3: Path `grade3` is required., grade4: Path `grade4` is required.

my Subscriber schema:

const mongoose = require("mongoose");
const subscriberSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  grade1: {
    type: String,
    required: true
  },
  grade2: {
    type: String,
    required: true
  },
  grade3: {
    type: String,
    required: true
  },
  grade4: {
    type: String,
    required: true
  }
});

subscriberSchema.methods.getInfo = function() {
  return `Name: ${this.name} grade1: ${this.grade1} grade2: ${this.grade2} grade3: ${this.grade3} grade4: ${this.grade4}`;
};

subscriberSchema.methods.findLocalSubscribers = function() {
  return this.model("Subscriber")
    .find({
      name: this.name
    })
    .exec();
};

the ejs form:

<div class="col-sm-6">
  <h1>Enter Student Name and Grades</h1>
  <p>Enter the student's name and grades for the first 4 CSC courses:</p>
  <form class="subscription-form" action="/subscribers/create" method="post">
    <input type="text" name="name" placeholder="Name" autofocus>
    <input type="text" grade1="grade1" placeholder="CSC141 Grade" required>
    <input type="text" grade2="grade2" placeholder="CSC142 Grade" required>
    <input type="text" grade3="grade3" placeholder="CSC240 Grade" required>
    <input type="text" grade4="grade4" placeholder="CSC241 Grade" required>
    <input type="submit" name="submit">
  </form>
</div>

the subscribers/create in the subscribers controller:

  create: (req, res, next) => {
    let subscriberParams = {
      name: req.body.name,
      grade1: req.body.grade1,
      grade2: req.body.grade2,
      grade3: req.body.grade3,
      grade4: req.body.grade4
    };
    Subscriber.create(subscriberParams)
      .then(subscriber => {
        res.locals.redirect = "/subscribers";
        res.locals.subscriber = subscriber;
        next();
      })
      .catch(error => {
        console.log(`Error saving subscriber: ${error.message}`);
        next(error);
      });
  },
...

i am new to mongoDB/nodejs/ejs so im wondering what i'm doing wrong.

Upvotes: 1

Views: 1064

Answers (1)

mickl
mickl

Reputation: 49945

It works for name because you're using HTML form name atrribute, try:

<input type="text" name="grade1" placeholder="CSC141 Grade" required>
<input type="text" name="grade2" placeholder="CSC142 Grade" required>
<input type="text" name="grade3" placeholder="CSC240 Grade" required>
<input type="text" name="grade4" placeholder="CSC241 Grade" required>

Upvotes: 1

Related Questions