mongdb migration - Tuong-Nguyen/JavaScript-Structure GitHub Wiki

mongodb-migration

Tool & library for migrating mongo database which can be used in integration with database. (https://github.com/emirotin/mongodb-migrations)

  • Migration: object with id (name of the migration), up method (function run to upgrade DB), down method (function run to downgrade the DB)
const userIds = ['211111111111111111111111', '211111111111111111111112', '211111111111111111111113', '211111111111111111111114'];

module.exports = {
  id: 'Create a user',

  existingUserIds: userIds,

  up(done){
    const users = [];
    for(let id of userIds){
      users.push(Object.assign({_id: id}, {name: 'Marcus', age: 42, height: 1.96}));
    }
    this.db.collection('users').insert(users, done);
  },

  down(done){
    // delete all users
    this.db.collection('users').remove({}, done);
  }
};
  • Run the migration
  before((done) => {
    const config = {
      host: process.env.MONGO_HOST,
      port: process.env.MONGO_PORT,
      db: process.env.MONGO_DB
    };
    // Create a migrator
    migrator = new mm.Migrator(config);
    // Add migration objects
    migrator.add(dbSetup);
    // migrate the DB
    migrator.migrate(done);
  });

  after((done) => {
    // roll back the migrations
    migrator.rollback(done);
  });

When the migration is done, it is recorded in _migrations collection (default) so that the migration is not run again if it is run. When the migration is roll backed, it is removed from this collection.