mongodb-migrator
Table of Contents
Installation
$ npm install -g mongodb-migrator
CLI usage
The package installs a single CLI executable — mdbmigrator
.
When installing locally to your project this executable can be found at
./node_modules/.bin/mdbmigrator
.
When installing globally the executable should automatically become accessible on your PATH.
Configuration
The configuration can be passed as a file (js or json):
// myconfig.json
mdbmigrator --config myconfig.json create mynewmigration
or cli arguments:
mdbmigrator --host 127.0.0.1 --port 27017 --db migrations create newmigrationname
Creating Migrations
The app simplifies creating migration stubs by providing a command
$ mdbmigrator create 'migration name'
This creates file migration-name.js
inside of the directory
defined in the configuration file.
Sample migration file
moduleexports = name: 'migration name' after: null { ; } { ; }
Where
migration name
— a unique name for migration.up
— a function used for forward migration.down
— a function used for backward migration.
Migration functions
The up
and down
functions take for two parameters db
- mongodb connection and callback cb
{ db;}
Running migrations
Applying all new migrations from the directory
(specified in
Configuration) by calling
$ mdbmigrator apply
Rollbacks are automatically called in the reverse order when an error occurs.
The library only runs migrations that:
- have
up
function defined, - were not ran before against this database.
- were rollback at any moment
Successfully applied migrations are recorded in the collection
specified in Configuration and successfully
canceled migrations remove the record from the collection
.
The migration process is stopped instantly if some migration fails (returns error in its callback), then beginning roll back process.
Check for new migrations
$ mdbmigrator check
Programmatic usage
The library also supports programmatic usage.
Start with require
'ing it:
var MongoMigrator = ; var migrator = options;
migrator
Using Next, you can use migrator instance as was described before:
// Load all migrationsvar migrationsArray = migrator; // Check for circularity's and count new migrationsmigrator; // Apply new migrationsmigrator;