Avedis Maroukian
Avedis Maroukian

Reputation: 1608

Unhandled rejection SequelizeDatabaseError: Cannot add foreign key constraint - Sequilize $ node

I have a simple model with only id in each model, and sometimes when I run the application to create the tables in the database, this error appears:

Unhandled rejection SequelizeDatabaseError: Cannot add foreign key constraint

Sometimes it works and sometimes it fails. I have tried with all the possibilites reading the docs but it happens the same, sometimes it works and sometimes no.

Any idea? The code is below.

Version of sequelize: 4.37.4

const Sequelize = require('sequelize');
const sequelize = new Sequelize('*****', '***', '**', {
  host: 'localhost',
  dialect: 'mysql',
  operatorsAliases: false,

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
})

const H = sequelize.define('H', {
});


const B = sequelize.define('B', {
},{
  timestamps: false
});


const V = sequelize.define('V', {
},{
timestamps: false
});

const P = sequelize.define('P', {
},{
timestamps: false
});

H.hasMany(P, { foreignKey: 'ide' });

P.hasMany(V, { foreignKey: 'ide' });

B.hasOne(P, { foreignKey: 'ide' });

H.sync({force: true})

P.sync({force: true})

B.sync({force: true})

V.sync({force: true})

Upvotes: 0

Views: 862

Answers (1)

eseom
eseom

Reputation: 86

node is async itself. The sync commands sent to server asynchronously, so we can not predict in what order the command will be executed.

you can write as

P.sync({force: true})
  .then(() => B.sync({force: true}))
  .then(() => V.sync({force: true}))
  .then(() => H.sync({force: true}))

or

sequelize.sync({force: true})

Upvotes: 1

Related Questions