John
John

Reputation: 1123

Handling migration in mongoose

This was my original Schema

var MessageSchema = new Schema({  
    attachments: [String]
});

This is my updated Schema

var MessageSchema = new Schema({  
    attachments: [{
        fileType: String,
        extension: String,
        url: String
    }]
});

Do I really have to create another model with the old Schema to find() the old documents and process the attachments and then using the updated schema model to save the document in order to successfully migrate my collection to the new Schema ?

Upvotes: 0

Views: 1977

Answers (1)

Alex Blex
Alex Blex

Reputation: 37038

I usually rename legacy field in the mongo shell: db.message.updateMany( {}, { $rename: { "attachments": "attachments_v1" } } ); and use

var MessageSchema = new Schema({
    attachments_v1: [String],  
    attachments: [{
        fileType: String,
        extension: String,
        url: String
    }]
});

with transition logic for some time to spread the load and modify the documents when they are being accessed. If the collection is small enough you can convert all of then in one go. If transition logic is trivial you may be able to do it from the shell. Otherwise, write a mongoose script to do the job.

Upvotes: 2

Related Questions