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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:06:03