Mongoose产品Schema关联到控制器时出现报错如何解决?
报错原因分析
你的Mongoose Schema定义中存在4处语法/规则使用错误,直接触发了运行报错:
images数组下的url字段,类型关键字type被错写为typrcategory字段的类型关键字type被错写为typrprice为Number类型,错误使用了仅适用于String类型的maxLength长度校验规则stock为Number类型,错误使用了仅适用于String类型的maxLength长度校验规则
解决方案
将对应错误的代码段替换为正确写法即可:
- 修正
images.url的type拼写:
images: [ { public_id: { type:String, required: true }, url:{ type:String, required: true } } ],
- 修正
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'] } },
- 修正
price的数值校验规则:
price: { type: Number, required: [true,'Please Enter Product Price'], max: [99999, 'Product Price Cannot Exceed 5 digits'] },
- 修正
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
相关产品推荐
相关产品推荐

