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

Mongoose Schema默认值失效,提示无效Schema配置问题求助

解决Mongoose Schema添加default值后出现“无效Schema配置”的问题

问题出在你role字段的配置拼写错误——把Mongoose要求的小写type写成了大写的Type,这才导致了“无效Schema配置”的错误,和default值本身无关。

修正后的代码:

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
    },
    password: {
        type: String,
        required: true,
    },
    phone: {
        type: Number,
        required: true,
    },
    dob: Date,
    address: {
        street: String,
        city: String,
        state: String,
        country: String,
        postalcode: Number,
    },
    profile: String,
    role: {   
        type: String, // 这里把Type改成小写的type
        enum: ['user','vendor'],
        default: 'user'
    },
    socialMedia: {
        facebook: String,
        instagram: String,
        twitter: String,
    },
},{
    timestamps: true,
})

const UserModel = mongoose.model('User',UserSchema)
module.exports = UserModel;

Mongoose的Schema字段配置项(比如type、required、enum等)都是区分大小写的,必须用小写开头的正确拼写,修正后添加default值的配置就能正常运行。

内容的提问来源于stack exchange,提问作者khesehang samsohang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:12:13