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?
A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.
Mongoose models and their schemas allow you to perform validation on the fields you expect or are required. But if you stop there then you've just got the equivalent of a relational schema.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With