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

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的类型要求。

修复方案

  1. 修正前端状态赋值逻辑
    把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
      });
    };
    
  2. 确认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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 06:22:41