Home > Software design >  How to create an array of objects with default values?
How to create an array of objects with default values?

Time:12-02

how to create an array of objects with default values?

const schema = new mongoose.Schema({
    login: {type: String, unique: true, required: true},
    password: {type: String, required: true},
    chatlist: [
        {
            channelname: {type: String, default: "frontend"},
            channelid: {type: String, default: "619a6bfe5b0931f1e5dbaf2c"}
        },
        {
            channelname: {type: String, default: "backend"},
            channelid: {type: String, default: "619a71002954ba23a951bb8f"}
        },
        {
            channelname: {type: String, default: "devops"},
            channelid: {type: String, default: "619d69c190a85a40893b6522"}
        },
    ]
})

this code above does not work
when a new user register i want to add a default chats to his profile
next thing is the user must be able to add/remove chats from the database
how should i do this? do the chats need to be an objects or documents?

CodePudding user response:

const schema = new mongoose.Schema({
    chatlist: {
      type: Array,
      defualt: []
    }
}) 

so to have a structure in the array I personally would make the request correct using error handling.

for more information visit this site

CodePudding user response:

didnt find any good solution so i just did this

const schema = new mongoose.Schema({
    login: {type: String, unique: true, required: true},
    password: {type: String, required: true},
    chatlist: [{
        channelname: String,
        channelid: String
    }]
})

const user = await MONGO_user.create({
    login: login,
    password: hashPassword,
})

user.chatlist.push(
    {
        channelname: "frontend",
        channelid: "619a6bfe5b0931f1e5dbaf2c"
    }, {
        channelname: "backend",
        channelid: "619a71002954ba23a951bb8f"
    }, {
        channelname: "devops",
        channelid: "619d69c190a85a40893b6522"
    })

await user.save()
  • Related