You need to enable JavaScript to run this app. 如何解决Mongoose报Path is required ValidationError错误(Node+Express场景)
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Mongoose报Path is required ValidationError错误(Node+Express场景)

问题根因

你的报错本质是Mongoose Schema定义的字段名和你传入模型实例的字段名大小写不匹配:

  • 模型中的RegSchema规定的必填字段为大写开头:Name、Email、Password、Number
  • 路由中实例化Register模型时,传入的对象键为小写开头:name、email、number、password
    Mongoose识别不到匹配的必填字段,认为四个字段全为undefined,因此触发必填校验报错。
修复方案

1. 统一字段大小写(二选一即可)

方案1:修改路由传值键名,和Schema定义保持一致

替换路由文件中实例化模型的代码:

const NewAdd = new Reg({
    Name: name,
    Email: email,
    Number: number,
    Password: password
})

方案2:修改Schema字段名,和传值的小驼峰格式保持一致(更符合JS编码规范,推荐)

替换模型文件中的Schema定义:

const RegSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  number: {
    type: Number,
    required: true
  }
});

2. 修复其他隐藏问题

  • 修正server.js中Mongoose连接配置的拼写错误:将useUnifiedTopologyL: true改为useUnifiedTopology: true(原配置多写了末尾的L)
  • Postman测试时需确认:请求方式为POST,Header携带Content-Type: application/json,Body选择raw/JSON格式,传入的字段名和你最终使用的命名规则完全一致,不要传空值。

内容的提问来源于stack exchange,提问作者kavindu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 23:30:04