You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose Schema必填字段验证失败问题求助

Mongoose必填字段验证异常:传入name字段仍触发ValidationError

问题背景

使用Mongoose定义Schema时,将name字段设置为必填项(required: true),编写创建产品接口后,发送包含name字段的POST请求(JSON内容为{"name":"Vaseline petrolatum Jelly"}),却触发ValidationError,提示路径name是必填项。已尝试相关解决方案但无效。

相关代码

控制器代码

const Product = require("../models/productModel");
// 创建产品
exports.createProduct = async (req, res, next) => {
  const product = await Product.create(req.body);

  res.status(201).json({
    success: true,
    product,
  });
};

模型代码(productModel.js)

const mongoose = require("mongoose");
const productSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true, // 标注的问题位置
  },
})

错误日志详情(翻译后)

this.$__.validationError = new ValidationError(this);
^

验证错误:产品验证失败: name: 路径`name`是必填项。
    在 Document.invalidate (C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\document.js:3289:32)
    在 C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\document.js:3050:17
    在 C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\schemaType.js:1388:9
    在 process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
  errors: {
    name: 验证器错误: 路径`name`是必填项。
        在 validate (C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\schemaType.js:1385:13)
        在 SchemaType.doValidate (C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\schemaType.js:1369:7)
        在 C:\Users\DELL\Downloads\react-learn\node_modules\mongoose\lib\document.js:3042:18
        在 process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: {
        validator: [匿名函数],
        message: '路径`name`是必填项。',
        type: 'required',
        path: 'name',
        fullPath: undefined,
        value: undefined
      },
      kind: 'required',
      path: 'name',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose#validatorError)]: true
    }
  },
  _message: '产品验证失败'
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:17:10