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

Mongoose产品Schema关联到控制器时出现报错如何解决?

报错原因分析

你的Mongoose Schema定义中存在4处语法/规则使用错误,直接触发了运行报错:

  • images数组下的url字段,类型关键字type被错写为typr
  • category字段的类型关键字type被错写为typr
  • price为Number类型,错误使用了仅适用于String类型的maxLength长度校验规则
  • stock为Number类型,错误使用了仅适用于String类型的maxLength长度校验规则
解决方案

将对应错误的代码段替换为正确写法即可:

  1. 修正images.url的type拼写:
images: [
    {
        public_id: {
            type:String,
            required: true
        },
        url:{
            type:String,
            required: true
        }
    }
],
  1. 修正category的type拼写:
category: {
    type: String,
    required: [true, 'Please select category for this Product'],
    enum: {
        values: [
            'Electronics',
            'Camera',
            'Laptop',
            'Accessories',
            'HeadPhones',
            'Food',
            'Books',
            'Clothes/Shoes',
            'Beauty/Health',
            'Sports',
            'Outdoor',
            'Home'
        ],
        required: [true, 'Please Select correct category for product']
    }
},
  1. 修正price的数值校验规则:
price: {
    type: Number,
    required: [true,'Please Enter Product Price'],
    max: [99999, 'Product Price Cannot Exceed 5 digits']
},
  1. 修正stock的数值校验规则,同时修正错误的提示文案:
stock: {
    type: Number,
    required: [true, 'Please enter Product stock number'],
    max:[99999, 'Product stock cannot exceed 5 digits'],
    default: 0
},

可选优化

原有Schema中多处提示文案存在拼写错误(如Exeed应为Exceed、connot应为cannot),可按需修改不影响代码运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:06:10