Mongoose Schema中folders数组默认值不生效,如何正确设置?
解决Mongoose数组字段默认值不生效的问题
你当前的folders字段定义有误,把默认值配置在了数组元素的选项里,而非数组字段本身的选项中,导致默认值无法生效。
错误原因分析
原代码中:
folders: [ { type: String, default: ['My notes', 'Todos', 'Projects', 'Journal', 'Reading list'], }, ],
这种写法表示folders是一个对象数组,每个对象包含一个String类型的属性,且给该属性设置了默认数组——这完全不符合你的需求,你需要的是folders本身就是字符串数组,默认值为指定的五个字符串。
修正后的Schema定义
将folders的配置改为直接定义字符串数组,并把default放在数组字段的配置项中:
const userSchema = mongoose.Schema({ id: { type: String, }, name: { type: String, required: true, }, email: { type: String, required: true, unique: true, }, password: { type: String, required: true, }, notes: [ { type: mongoose.Types.ObjectId, ref: 'Note', }, ], folders: { type: [String], // 明确指定为字符串数组类型 default: ['My notes', 'Todos', 'Projects', 'Journal', 'Reading list'] // 默认值直接配置在此处 }, });
验证效果
创建新用户时,若不传入folders字段,Mongoose会自动为该字段填充指定的默认数组:
const newUser = new User({ name: 'Test User', email: 'test@example.com', password: '123456' }); await newUser.save(); // 此时newUser.folders的值为 ['My notes', 'Todos', 'Projects', 'Journal', 'Reading list']
内容的提问来源于stack exchange,提问作者BLIND
相关产品推荐
相关产品推荐

