Mongoose ValidationError:验证失败:需要路径

Posted

技术标签:

【中文标题】Mongoose ValidationError:验证失败:需要路径【英文标题】:Mongoose ValidationError: validation failed: Path is required 【发布时间】:2020-08-20 19:55:56 【问题描述】:

当我在我的 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>

订阅者/在订阅者控制器中创建:

  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 的新手,所以我想知道我做错了什么。

【问题讨论】:

【参考方案1】:

它适用于name,因为您使用的是 html 表单 name 属性,请尝试:

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

【讨论】:

以上是关于Mongoose ValidationError:验证失败:需要路径的主要内容,如果未能解决你的问题,请参考以下文章

UnhandledPromiseRejectionWarning: ValidationError

ValidationError:验证失败猫鼬

mongoose 和 node.js 中的验证错误(错误如下)

表单 ValidationError 和错误代码

ValidationError:转换为 [undefined] 失败

在引发 ValidationError 期间“未定义全局名称'_'”