Why Sequelizejs is inserting null for foreign key field?

Posted on

If you are using Sequlizejs for working with Postgres or MySQL with foreign key columns not set in the model definition like shown below:

module.exports = (sequelize, DataTypes) => {
  const Wing = sequelize.define(
    'Wing',
    {
      name: { type: DataTypes.STRING, allowNull: false },
      description: { type: DataTypes.TEXT },
      is_active: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: true
      }
    },
    {
      underscored: true,
      tableName: 'wings',
      paranoid: true
    }
  );
  Wing.associate = models => {
    Wing.belongsTo(models.Village);
    Wing.hasMany(models.Accommodation);
  };
  return Wing;
};

and you try to use create or bulkCreate on the model by providing the values of all fields including foreign key column like:

 {
    name: 'Wing 1',
    village_id: 1
  }

Then it must be failing to insert proper value i.e 1 for village_id and putting null there, This happens because although Sequelizejs is a good ORM library, it ignores some basic things which it teaches in the starting.

So, to fix this error, you have to manually specify the foreign key column in the model definition i.e:

village_id: { type: DataTypes.INTEGER }

making the full model definition as:

module.exports = (sequelize, DataTypes) => {
  const Wing = sequelize.define(
    'Wing',
    {
      name: { type: DataTypes.STRING, allowNull: false },
      description: { type: DataTypes.TEXT },
      village_id: { type: DataTypes.INTEGER },  // <<<--- Here
      is_active: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: true
      }
    },
    {
      scopes: {
        active: {
          where: {
            is_active: true
          }
        }
      },
      underscored: true,
      tableName: 'wings',
      paranoid: true
    }
  );
  Wing.associate = models => {
    Wing.belongsTo(models.Village);
    Wing.hasMany(models.Accommodation);
  };
  return Wing;
};

This will fix the issue!

Happy hacking!

Leave a Reply

Your email address will not be published. Required fields are marked *