Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly handle mongoose schema migrations?

I'm completely new to MongoDB & Mongoose and can't seem to find an answer as to how to handle migrations when a schema changes.

I'm used to running migration SQL scripts that alter table structure and any underlying data that needs to be changed. This typically involves DB downtime.

How is this typically handled within MongoDB/Mongoose? Any gotcha's that I need to be aware of?

like image 397
hafichuk Avatar asked Aug 18 '13 03:08

hafichuk


People also ask

Can Mongoose schema be changed?

There's nothing built into Mongoose regarding migrating existing documents to comply with a schema change. You need to do that in your own code, as needed.

What is migration in Mongoose?

migrate-mongoose is a migration framework for projects which are already using mongoose. Most other migration frameworks: Use a local state file to keep track of which migrations have been run: This is a problem for PaS providers like heroku where the file system is wiped each time you deploy.

What does $Set do in Mongoose?

The $set operator replaces the value of a field with the specified value.


2 Answers

In coming across this and reasonably understanding how migrations work on a relational database, MongoDB makes this a little simpler. I've come to 2 ways to break this down. The things to consider when dealing with data migrations in MongoDB (not all that uncommon from RDBs) are:

  • Ensuring local test environments do not break when a developer merges the latest from the project repository
  • Ensuring any data is correctly updated on the live version regardless if a user is logged in or out if authentication is used. (Of course if everyone is automatically logged out when an upgrade is made, then only worrying about when a user logs in is necessary).

1) If your change will log everyone out or application downtime is expected then the simple way to do this is have a migration script to connect to local or live MongoDB and upgrade the correct data. Example where a user's name is changed from a single string to an object with given and family name (very basic of course and would need to be put into a script to run for all developers):

Using the CLI:

mongod use myDatabase db.myUsers.find().forEach( function(user){     var curName = user.name.split(' '); //need some more checks..      user.name = {given: curName[0], family: curName[1]};     db.myUsers.save( user ); }) 

2) You want the application to migrate the schemas up and down based on the application version they are running. This will obviously be less of a burden for a live server and not require down time due to only upgrading users when they use the upgraded / downgraded versions for the first time.

If your using middleware in Expressjs for Nodejs:

  • Set an app variable in your root app script via app.set('schemaVersion', 1) which will be used later to compare to the users schema version.
  • Now ensure all the user schemas have a schemaVersion property as well so we can detect a change between the application schema version and the current MongoDB schemas for THAT PARTICULAR USER only.
  • Next we need to create simple middleware to detect the config and user version

    app.use( function( req, res, next ){   //If were not on an authenticated route   if( ! req.user ){     next();     return;   }   //retrieving the user info will be server dependent   if( req.user.schemaVersion === app.get('schemaVersion')){     next();     return;   }    //handle upgrade if user version is less than app version    //handle downgrade if user version is greater than app version    //save the user version to your session / auth token / MongoDB where necessary }) 

For the upgrade / downgrade I would make simple js files under a migrations directory with an upgrade / downgrade export functions that will accept the user model and run the migration changes on that particular user in the MongoDB. Lastly ensure the users version is updated in your MongoDB so they don't run the changes again unless they move to a different version again.

like image 72
Ryan Q Avatar answered Sep 27 '22 21:09

Ryan Q


If you're used to SQL type migrations or Rails-like migrations then you'll find my cli tool migrate-mongoose the right fit for you.

It allows you to write migrations with an up and a down function and manages the state for you based on success and failure of your migrations.

It also supports ES6 if you're using ES 2015 syntax.

You get access to your mongoose models via the this object, making it easy to make the changes you need to your models and schemas.

like image 31
mrBorna Avatar answered Sep 27 '22 23:09

mrBorna