Syncing Sequelize Schemas with Foreign Keys

thumb image-post mask

"The Sequelize library provides easy access to MySQL, MariaDB, SQLite or PostgreSQL databases by mapping database entries to objects and vice versa. To put it in a nutshell, it's an ORM (Object-Relational-Mapper). The library is written entirely in JavaScript and can be used in the Node.JS environment." Sequelize

I recently found myself in the position of having defined several Sequelize models, many of which were associated via foreign key relationships. After a recent schema change, I attempted to sync the newly updated schemas with MySQL by following the example laid out in the documentation:

    'force': true
}).complete(function(err) {
    if (err) {
        console.log('An error occurred while synchronizing the table:', err)
    } else {
        console.log('It worked!')

I was greeted with this error:

ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails Use --force to continue  

According to docs, this issue should have been avoided as a result of the force: true option being passed, but it wasn't. As it turns out (and this isn't mentioned in the docs), Sequelize creates a "pool" of database connections by default - which is normally a good thing, but which causes issues when attempting to synchronize schemas. The answer is to disable pooling when sychronizing schemas, as shown below:

var sequelize = new Sequelize('db', 'user', 'pass', {  
    'pool': false

With pooling disabled, your schemas should synchronize without any further problems.