0
votes

'use strict';

module.exports = {
	up: (queryInterface, Sequelize) => {
		return Promise.all([
			queryInterface.addColumn('Posts', 'userAccountId', {
				type: Sequelize.INTEGER,
			}),
			queryInterface.addColumn('Posts', 'postTopicId', {
				type: Sequelize.INTEGER,
			}),
			queryInterface.addConstraint('Posts', ['userAccountId'], {
				type: 'foreign key',
				name: 'userAccountId',
				references: {
					table: 'UserAccounts',
					field: 'id',
				},
				onDelete: 'no action',
				onUpdate: 'no action',
			}),
			queryInterface.addConstraint('Posts', ['postTopicId'], {
				type: 'foreign key',
				name: 'postTopicId',
				references: {
					table: 'PostTopics',
					field: 'id',
				},
				onDelete: 'no action',
				onUpdate: 'no action',
			}),
		]);
	},

	down: (queryInterface, Sequelize) => {
		return Promise.all([
			queryInterface.removeColumn('Posts', 'userAccountId'),
			queryInterface.removeColumn('Posts', 'postTopicId'),
			queryInterface.removeConstraint('Posts', 'userAccountId'),
			queryInterface.removeConstraint('Posts', 'postTopicId'),
		]);
	},
};

When I run the command npx sequelize db:migrate, I receive this error "ERROR: column "postTopicId" referenced in foreign key constraint does not exist"

I dont what is wrong, all the other migrations running ok. I'm running my database in a docker container.

1

1 Answers

2
votes

You should not use Promise.all while executing queries that modifying structure and depending on each other. Promise.all does not guarantee an original order of execution queries. Use transaction and sequential execution:

return queryInterface.sequelize.transaction(async transaction => {
            await queryInterface.addColumn('Posts', 'userAccountId', {
                type: Sequelize.INTEGER,
            }, { transaction })
            await queryInterface.addColumn('Posts', 'postTopicId', {
                type: Sequelize.INTEGER,
            }, { transaction })
            await queryInterface.addConstraint('Posts', ['userAccountId'], {
                type: 'foreign key',
                name: 'userAccountId',
                references: {
                    table: 'UserAccounts',
                    field: 'id',
                },
                onDelete: 'no action',
                onUpdate: 'no action',
            }, { transaction })
            await queryInterface.addConstraint('Posts', ['postTopicId'], {
                type: 'foreign key',
                name: 'postTopicId',
                references: {
                    table: 'PostTopics',
                    field: 'id',
                },
                onDelete: 'no action',
                onUpdate: 'no action',
            }, { transaction })
        });