MongoDB is a schemaless database, so why would one need migrations? The answer is that there are needs, even in the non-relational world. Some examples:

  • removing mognodb indexes created by mongoose
  • populating system data (not fixtures)
  • removing attributes that have a different mongoose schema structure
  • seeding system users
  • removing system users :)
  • you get the point, bunch of reasons

I searched around and found that mongo-migrate fit the bill pretty well. To get it installed:

> npm install mongo-migrate

now you can create a new migration "add-images"

> node ./node_modules/mongo-migrate/index.js -runmm create add-images
  create : /Users/azuercher/workspace/test/migrations/0005-add-images.js

this will create a file in your local "migrations" directory, ex: migrations/0005-add-images.js. You just use a commonjs implementation and export an "up" and "down" function, which each pass in a mongodb database and of course a callback. So you can do pretty much anything you want with the mongodb driver. I do recommend using the high level mongodb API instead of your mongoose models since those can mutate over time and cause problems.

var mongodb = require('mongodb');

exports.up = function(db, next){
    next();
};

exports.down = function(db, next){
    next();
};

create a default-config.json file with your host, port and db, and optionally your creds as well

{
	"mongoAppDb": {
		"host": "localhost",
		"db": "mytestdb",
		"port": 27017

	}
}

To run the migration:

node ./node_modules/mongo-migrate/index.js -runmm up

To rollback:

node ./node_modules/mongo-migrate/index.js -runmm down

NOTE that you can add the -cfg parameter when you run to specify a different config than the default (ex: "prod-config.json"):

node ./node_modules/mongo-migrate/index.js -runmm -cfg prod-config.json up