簡體   English   中英

ZCCADCDEDB567ABAE643E15DCF0974E503Z ValidationError:驗證失敗:需要路徑

[英]Mongoose ValidationError: validation failed: Path is required

當我在我的 web 應用程序的 ejs 表單中輸入與我的 mongoDB 架構有關的信息時出現錯誤:

我得到的錯誤:

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

我的訂閱者架構:

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

ejs 形式:

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

訂閱者/在訂閱者 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);
      });
  },
...

我是 mongoDB/nodejs/ejs 的新手,所以我想知道我做錯了什么。

它適用於name ,因為您使用的是 HTML 表單名稱屬性,請嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM