How to Add, Delete new Columns in Sequelize CLI

后端 未结 7 1897
刺人心
刺人心 2020-12-07 16:43

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

7条回答
  •  情书的邮戳
    2020-12-07 17:17

    Per Pter suggestion to wrap Promise in a transaction, here's a sample using async/await and a transaction (from docs with bug fix when creating an index):

    'use strict';
    
    module.exports = {
        async up(queryInterface, Sequelize) {
            const transaction = await queryInterface.sequelize.transaction();
            try {
                await queryInterface.addColumn(
                    'Todo',
                    'completed',
                    {
                        type: Sequelize.STRING,
                    },
                    { transaction }
                );
    
                await queryInterface.addIndex(
                    'Todo',
                    {
                        fields: ['completed'],
                        unique: true,
                    },
                    { transaction }
                );
    
                await transaction.commit();
            } catch (err) {
                await transaction.rollback();
                throw err;
            }
        },
    
        async down(queryInterface, Sequelize) {
            const transaction = await queryInterface.sequelize.transaction();
            try {
                await queryInterface.removeColumn(
                    'Todo',
                    'completed',
                    { transaction }
                );
    
                await transaction.commit();
            } catch (err) {
                await transaction.rollback();
                throw err;
            }
        }
    };
    

提交回复
热议问题