How to Add New Fields to Existing Sequelize Migration

Chinedu Orie - Feb 28 '20 - - Dev Community

Sometimes you realize that you need to add some new fields to an existing sequelize migrations. This is especially important for production apps where refreshing the migration is not an option. Below is a quick guide on how to implement it.

Let's assume you want to add some new fields to Users table; below are the steps.

Step 1 - Create a new migration

npx sequelize-cli migration:create --name modify_users_add_new_fields
Enter fullscreen mode Exit fullscreen mode

Step 2 - Edit the migrations to suit the need

module.exports = {
  up(queryInterface, Sequelize) {
    return Promise.all([
      queryInterface.addColumn(
        'Users', // table name
        'twitter', // new field name
        {
          type: Sequelize.STRING,
          allowNull: true,
        },
      ),
      queryInterface.addColumn(
        'Users',
        'linkedin',
        {
          type: Sequelize.STRING,
          allowNull: true,
        },
      ),
      queryInterface.addColumn(
        'Users',
        'bio',
        {
          type: Sequelize.TEXT,
          allowNull: true,
        },
      ),
    ]);
  },

  down(queryInterface, Sequelize) {
    // logic for reverting the changes
    return Promise.all([
      queryInterface.removeColumn('Users', 'linkedin'),
      queryInterface.removeColumn('Users', 'twitter'),
      queryInterface.removeColumn('Users', 'bio'),
    ]);
  },
};
Enter fullscreen mode Exit fullscreen mode

Step 3 - Update the model with the new fields

Step 4 - Run migration

npx sequelize-cli db:migrate

Enter fullscreen mode Exit fullscreen mode

That is it, you have successfully added new fields to an existing migration.

. . . . . . . . . . . . . . . . . . . .
Terabox Video Player