Home > Software design >  Save array of ObjectId's using Mongoose's Schema
Save array of ObjectId's using Mongoose's Schema

Time:12-08

I have a Mongoose Schema like:

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

And a small function to test whether it saves the data as desired which contains:

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')
    })

It saves everything correctly except the array ObjectIds (commands). What is going wrong here?

CodePudding user response:

You've written the commands in schema with nested array. Try with single array:

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

CodePudding user response:

Try this:

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