axios.post提交数据搭配Mongoose Schema时出现Internal Server Error报错
问题排查与解决步骤
1. 第一步先捕获具体错误信息
当前的500是泛化服务错误,优先给路由添加错误捕获逻辑,打印具体报错内容定位问题:
router.post("/", upload, function(req, res, next) { try { const obj = JSON.parse(req.body.obj) console.log('解析后的提交数据:', obj) // 先校验前端提交的字段完整性、类型正确性 let newPostData = new newPostSchema({ id: obj.id, name: obj.name, price: obj.price, salePrice: obj.salePrice, discount: obj.discount, pictures: obj.pictures, shortDetails: obj.shortDetails, description: obj.description, stock: obj.stock, new: obj.new, sale: obj.sale, category: obj.category, colors: obj.colors, size: obj.size, tags: obj.tags, rating: obj.rating, variants: obj.variants, }); let postData = { file: req.files, data: newPostData, }; res.send(postData) } catch (err) { console.error('服务报错详情:', err) // 服务端控制台会输出具体错误原因 res.status(500).send({error: err.message}) } });
重启服务后再次发起请求,查看服务端控制台打印的错误即可精准定位问题。
2. 常见错误对应修复方案
① Schema导入错误
检查路由文件顶部导入newPostSchema的代码是否正确,示例正确写法:
// 路径替换为你实际存放Schema文件的相对路径 const { newPostSchema } = require('./models/newPostSchema.js')
导入时变量名写错、文件路径错误,都会导致实例化Schema时报错。
② 数据类型不匹配
对比Schema定义的字段类型和前端提交的obj对应字段类型,常见不匹配场景:
- Schema中
new、sale字段为Boolean类型,前端传递的是字符串"true"/"false",JSON.parse后仍为字符串不符合类型要求 - 数字类型字段(id、price、stock等)前端传递了字符串格式的数字,比如
id: "123"而非id: 123 - 数组类型字段(pictures、colors、size等)前端传递了非数组值,比如单个字符串而非数组包裹的字符串
修复方法:实例化Schema前先做类型转换,示例:
const obj = JSON.parse(req.body.obj) const formatObj = { ...obj, id: Number(obj.id), price: Number(obj.price), new: Boolean(obj.new), sale: Boolean(obj.sale), // 其他需要转换类型的字段按需补充 } let newPostData = new newPostSchema(formatObj)
③ 上传文件路径未同步更新
当前代码中pictures字段直接使用了前端传的obj.pictures,如果需求是要把上传的文件路径存到该字段,需要手动替换:
// 路径提取规则根据你upload中间件的返回结构调整 const filePaths = req.files.map(file => file.path) let newPostData = new newPostSchema({ ...formatObj, pictures: filePaths // 替换为实际上传后的文件路径数组 })
3. 补充注意项
如果后续需要把数据写入MongoDB,实例化Schema之后需要调用save()方法才会完成入库:
await newPostData.save()
调用时需要把路由回调改为async函数。
内容的提问来源于stack exchange,提问作者Rizwan Ali
相关产品推荐
相关产品推荐

