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

Mongoose Schema配置错误求助:启动Node时程序崩溃

问题排查与修复方案

核心崩溃原因

你的category字段配置存在语法错误:将类型声明type: String误写为category: String,导致Mongoose无法识别字段类型,进而错误地把required数组解析为嵌入式文档数组,触发Could not determine the embedded type for array category.required报错。

修复后的category字段:

category:{
    type:String,
    required:[true,"Please Enter Product Category"],
},

其他需修正的细节问题

  • 导出语句拼写错误:最后一行的mosule.export应改为module.exports,否则无法正确导出模型。
  • Number类型校验规则误用:price和stock是数值类型,maxLength是针对字符串的校验规则,需替换为max;同时stock的错误提示里"excee"拼写错误,应改为"exceed"。
  • 冗余依赖:代码中引入的const { DataView } = require("webidl-conversions");未被使用,可删除以减少不必要的依赖。

完整修复后的代码

const mongoose = require("mongoose");

const productSchema = new mongoose.Schema({
    name:{
        type:String,
        required:[true,"Please Enter Product Name"],
        trim:true
    },
    description:{
        type:String,
        required:[true,"Please Enter Product Description"]
    },
    price:{
        type:Number,
        required:[true,"Please Enter Product Price"],
        max:[999999,"Price cannot exceed 999999"]
    },
    rating:{
        type:Number,
        default:0
    },
    images:[
        {
            public_id:{
                type:String,
                required:true,
            },
            url:{
                type:String,
                required:true,
            }
        }
    ],
    category:{
        type:String,
        required:[true,"Please Enter Product Category"],
    },
    stock:{
        type:Number,
        required:[true,"Please Enter Product Stock"],
        max:[9999,"Stock cannot exceed 9999"],
        default:1
    },
    numOfReviews:{
        type:Number,
        default:0
    },
    reviews:[
        {
            name:{
                type:String,
                required:true,
            },
            rating:{
                type:Number,
                required:true,
            },
            comment:{
                type:String,
                required:true,
            }

        }
    ],
    createdAt:{
        type:Date,
        default:Date.now
    }
})

module.exports = mongoose.model("Product",productSchema);

内容的提问来源于stack exchange,提问作者Parth Movaliya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:42:26