【问题标题】:Save array of ObjectId's using Mongoose's Schema使用 Mongoose Schema 保存对象数组
【发布时间】:2021-12-08 00:50:38
【问题描述】:

我有一个 Mongoose 架构,例如:

const Role = new Schema({
    guildID: {
        type: Schema.Types.ObjectId,
        ref: 'guilds',
        required: true
    },
    roles: {
        owner: {
            id: {
                type: Number,
                required: false
            },
            commands: [[Schema.Types.ObjectId]]
        }
    }
})

还有一个小函数来测试它是否按需要保存数据,其中包含:

const roleTest = new Role({
        guildID: "61a679e18d84bff40c2f88fd",
        roles: {
            owner: {
                id: 123456789
            },
            commands: [
                "61af57d828b9fd5a07dbdcba",
                "61af5a6728b9fd5a07dbdcbb",
                "61af5ab728b9fd5a07dbdcbc"
            ]
        }
    })

    roleTest.save((err, doc) => {
        if (err) return res.sendStatus(500)
        console.log('Done')
    })

它会正确保存除数组 ObjectIds(命令)之外的所有内容。这里出了什么问题?

【问题讨论】:

    标签: javascript mongodb mongoose mongoose-schema


    【解决方案1】:

    您已经在带有嵌套数组的架构中编写了 commands。尝试使用单个数组:

    {
    commands: [Schema.Types.ObjectId],
    }
    

    【讨论】:

      【解决方案2】:

      试试这个:

      commands: [
      { type: mongoose.Schema.Types.ObjectId }
      ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-17
        • 2019-03-05
        • 2017-06-26
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        • 2016-05-21
        • 2019-09-11
        相关资源
        最近更新 更多