How to Add, Delete new Columns in Sequelize CLI

Gijo Varghese picture Gijo Varghese · Sep 22, 2017 · Viewed 65.2k times · Source

I've just started using Sequelize and Sequelize CLI

Since it's a development time, there are a frequent addition and deletion of columns. What the best the method to add a new column to an existing model?

For example, I want to a new column 'completed' to Todo model. I'll add this column to models/todo.js. Whats the next step?

I tried sequelize db:migrate

not working: "No migrations were executed, database schema was already up to date."

Answer

Maria Ines Parnisari picture Maria Ines Parnisari · Sep 22, 2017

If you are using sequelize-cli you need to create the migration first. This is just a file that tells the engine how to update the database and how to roll back the changes in case something goes wrong. You should always commit this file to your repository

$ sequelize migration:create --name name_of_your_migration

The migration file would look like this:

module.exports = {
  up: function(queryInterface, Sequelize) {
    // logic for transforming into the new state
    return queryInterface.addColumn(
      'Todo',
      'completed',
     Sequelize.BOOLEAN
    );

  },

  down: function(queryInterface, Sequelize) {
    // logic for reverting the changes
    return queryInterface.removeColumn(
      'Todo',
      'completed'
    );
  }
}

And then, run it:

$ sequelize db:migrate