Update schema without dropping collection in mongodb

Viewed 1107

I have schema that look like :

const UserSchema = Schema({
    _id: mongoose.Schema.Types.ObjectId,
    userName: {
        type: String,
        required: true,
    },
    userPhoneNumber: {
        type: String,
    },
    role:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:Role
    }]
});

With this schema I have added document in DB with role:[]. But now as per requirement, I need to update schema without dropping the existing collection. I need to update data with all fields are same except role. I want to update the existing record with role as

role:[{
    department:{
        type:string
    },
    roleNames:[{
        type:type: mongoose.Schema.Types.ObjectId,
        ref:Role
    }]
}]

so how can I update the schema without dropping the collection.

1 Answers

MongoDB is born to solve this type of schema problem only thing you need to do is to add another field with a default value just like that

old Schema:

new Schema({
    name: { type: string }
})

new Schema with birthplace field :

new Schema({
    name: { type: string },
    birthplace: { type: string, required: true, default: 'neverborn' }
});
Related