node.jsdatabaseormsequelize.jssequelize-cli

How to add column in Sequelize existing model?


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 :)


Solution

  • Suvethan's answer is correct, but the migration code snippet has a minor bug. Sequelize migrations expect a promise to be returned, which is noted in a comment in the generated migration skeleton:

    Add altering commands here.
    Return a promise to correctly handle asynchronicity.
    
    Example:
    return queryInterface.createTable('users', { id: Sequelize.INTEGER });
    

    So, returning an array of promises can potentially lead to unexpected results because there's no guarantee that all of the promises will have resolved before moving on to the next migration. For most operations you're unlikely to run into any issues since most things will complete before Sequelize closes the process. But I think it's better to be safe than sorry when it comes to database migrations. You can still leverage the array of promises; you just need to wrap it in a Promise.all call.

    Suvethan's example, but with Promise.all:

    module.exports = {
      up: function (queryInterface, Sequelize) {
        return Promise.all([
          queryInterface.addColumn(
            'Users',
            'gender',
             Sequelize.STRING
           ),
          queryInterface.addColumn(
            'Users',
            'age',
            Sequelize.STRING
          )
        ]);
      },
    
      down: function (queryInterface, Sequelize) {
        // logic for reverting the changes
      }
    };