How to add column in Sequelize existing model?

Ajay Poriya picture Ajay Poriya · Apr 18, 2018 · Viewed 16.2k times · Source

I have added a model and a migration file using this command

node_modules/.bin/sequelize model:generate --name User --attributes firstName:string,lastName:string,email:string

Now I wanted to add few more fields like gender and age in to the existing table(model). I changed model manually and fire this command

node_modules/.bin/sequelize db:migrate

But it is responding that "No migrations were executed, database schema was already up to date. "

User.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

Thank you in advance :)

Answer

Suvethan Nantha picture Suvethan Nantha · Apr 18, 2018

In order to add new fields to the table,we should use migration skeleton as shown below.

sequelize migration:create --name Users

Open the migration file and add the below codes

module.exports = {
  up: function (queryInterface, Sequelize) {
    return [ queryInterface.addColumn(
              'Users',
              'gender',
               Sequelize.STRING
             ),
            queryInterface.addColumn(
             'Users',
             'age',
             Sequelize.STRING
          )];
  },

  down: function (queryInterface, Sequelize) {
    // logic for reverting the changes
  }
};

Then just run the migration

node_modules/.bin/sequelize db:migrate

Note: The passed queryInterface object can be used to modify the database. The Sequelize object stores the available data types such as STRING or INTEGER.

Full list of methods in Query Interface

I hope this will help you. If you have any issues let me know.