使用Mongoose Schema保存ObjectId数组时commands字段存储失败问题
问题原因
有两个核心错误导致commands字段无法正常存储:
- 字段层级不匹配
Schema定义中commands是嵌套在roles.owner下的属性,但你在实例化Role模型时,把commands写到了和owner平级的roles属性下,Mongoose会自动忽略未在Schema中定义的字段,这部分数据直接被丢弃。 - Schema数组类型定义错误
你当前写的commands: [[Schema.Types.ObjectId]]是二维数组类型(数组的元素也要求是数组),但你传入的是一维字符串数组,如果你只需要存储一维ObjectId数组,应该调整定义为commands: [Schema.Types.ObjectId]。
修正后代码示例
调整后的Schema
const Role = new Schema({ guildID: { type: Schema.Types.ObjectId, ref: 'guilds', required: true }, roles: { owner: { id: { type: Number, required: false }, // 修改为一维ObjectId数组 commands: [Schema.Types.ObjectId] } } })
调整后的实例化代码
const roleTest = new Role({ guildID: "61a679e18d84bff40c2f88fd", roles: { owner: { id: 123456789, // commands放到owner层级下 commands: [ "61af57d828b9fd5a07dbdcba", "61af5a6728b9fd5a07dbdcbb", "61af5ab728b9fd5a07dbdcbc" ] } } }) roleTest.save((err, doc) => { if (err) return res.sendStatus(500) console.log('Done') })
内容的提问来源于stack exchange,提问作者Sylent
相关产品推荐
相关产品推荐

