Changing schemas in mongoDB/mongoose
I开发者_开发问答 am getting started with mongoDB and mongoose. I was wondering how people manage evolving schemas. For example if i started with a schema like this:
user_ID : 123,
user_firstName : 'bob',
user_lastName : 'smith'
And evolved it to something like this:
user_ID: 123,
user_name: [first:'bob', last:'smith']
How could I update or manage old records that were established using the old schema design?
One approach to migrating document schemas involving simple data transformations would be to use $exists to find documents that are missing the new fields and migrate them.
For example, transforming firstName and lastName into a new user_name field:
db.mycollection.find( { user_name : { $exists : false } } ).forEach(
function (doc) {
doc.user_name = {'first': doc.user_firstName, 'last': doc.user_lastName};
// Remove old properties
delete doc.user_firstName;
delete doc.user_lastName;
// Save the updated document
db.mycollection.save(doc);
}
)
For more complex migrations some tools that could be helpful are:
- schema.js or variety for analyzing the current schema of a collection
- JSV: JSON Schema Validator for validating documents
精彩评论