Mongoose ValidationError报错解决:类型转换失败问题
解决Mongoose ValidationError:字段类型不匹配问题
问题描述
开发电商网站后台管理面板的商品添加功能时,尝试将商品信息存入MongoDB集合,触发Mongoose的
ValidationError,提示name、category、new_price、old_price字段无法将Array类型转换为对应的数据类型(String/Number)。
原因分析
- 前端React代码的
changeHandler函数错误地将表单输入值以数组形式([e.target.value])存入productDetails状态,导致后端接收的字段类型为数组,与Mongoose Schema定义的String/Number类型不匹配。 - 价格字段(
new_price、old_price)在前端输入时为字符串类型,未转换为Number类型,不符合Schema的类型要求。
修复方案
修正前端状态赋值逻辑
把changeHandler中数组形式的赋值改为直接存储输入值,同时对价格字段做类型转换:const changeHandler = (e) => { let inputValue = e.target.value; // 针对价格字段转换为Number类型 if (['new_price', 'old_price'].includes(e.target.name)) { inputValue = Number(inputValue); } setProductDetails({ ...productDetails, [e.target.name]: inputValue }); };确认Mongoose Schema定义
确保Schema中的字段类型与预期一致,示例如下:const mongoose = require('mongoose'); const productSchema = new mongoose.Schema({ name: { type: String, required: true }, category: { type: String, required: true }, new_price: { type: Number, required: true }, old_price: { type: Number, required: true }, // 其他商品字段(如图片、描述等) }); module.exports = mongoose.model('Product', productSchema);
内容的提问来源于stack exchange,提问作者S M Rafizul Haque
相关产品推荐
相关产品推荐

