How to add column in Sequelize existing model?

▼魔方 西西 提交于 2019-12-03 14:09:50
David Blanchard

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
  }
};

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!