Question

In Sequelize.js, i have created an example migration file:

module.exports = {
  up: function(migration, DataTypes, done) {
    // add altering commands here, calling 'done' when finished
    migration.createTable('Users', {
        id: {
            type: DataTypes.INTEGER, 
            primaryKey: true, 
            autoIncrement: true, 
        }, 
        createdAt: {
          type: DataTypes.DATE
        },
        updatedAt: {
          type: DataTypes.DATE
        },
        firstname: DataTypes.STRING, 
        lastname: DataTypes.STRING,
        email: DataTypes.STRING, 
        password: DataTypes.STRING,
    });
    done()
  },
  down: function(migration, DataTypes, done) {
    // add reverting commands here, calling 'done' when finished
    done()
  }
}

Could someone explain the use cases and possible implementation of both up and down functionality?

Thank you!

Was it helpful?

Solution

You got to see the thing like if your database have 2 different "states", before migration and after migration.

Before you start any migration you don't have any Users table, so lets say that your database is in "state 1".

When you run the up migrations ( sequelize db:migrate ) you pass your database to "state 2" ( now you have the Users table in your database ).

If anything went wrong or you changed your mind about this migration, you can go back to "state 1" again by running the down functionality ( sequelize db:migrate:undo ) doing the opposite of the up functionality.

In this case its simple, if you are creating a Users, to reverse you have only to delete it and you go back to "state 1" again.

module.exports = {

    up: function(migration, DataTypes, done) {

        // add altering commands here, calling 'done' when finished
        migration.createTable( 'Users', {

            id: {
                type: DataTypes.INTEGER,
                primaryKey: true,
                autoIncrement: true,
            },
            createdAt: {
                type: DataTypes.DATE
            },
            updatedAt: {
                type: DataTypes.DATE
            },
            firstname: DataTypes.STRING,
            lastname: DataTypes.STRING,
            email: DataTypes.STRING,
            password: DataTypes.STRING,

        })
        .nodeify( done );
    },

    down: function(migration, DataTypes, done) {
    // add reverting commands here, calling 'done' when finished

        migration.dropTable('Users')
        .nodeify( done );

    }

};

Per example, if you were going to delete the Users table instead of creating it, you just have to exchange the up and down code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top