Saturday, 22 April 2017

Sequelizejs produces wrong column name for Foreign Key in insert query with belongsTo relationship

I have a sequelize model for Organisation table in PostgreSQL dialect.

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Organisation = sequelize.define('Organisation', {
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    }, 
    type: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    numUsers: {
      type: DataTypes.INTEGER,
      allowNull: false,
    },
    expDate:  {
      type: DataTypes.DATE,
      allowNull: false
    }
  }, {
    classMethods: {
      associate: function(models) {
        Organisation.belongsTo(models.User);
      }
    }
  });
  return Organisation;
};

And another model called Users for Users Table:

'use strict';


module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    passwordHash: DataTypes.STRING,
    passwordResetToken: DataTypes.STRING
  },
  {
    classMethods: {
      associate: function(models) {

        User.belongsTo(models.Organisation);
      }
    }
  });
  return User;
};

When I create a User with Organisation in a REST API like this:

DB.User.create({
      name: attributes.primaryContactName,
      email: attributes.primaryContactEmail,
      role: 10,
      Organisation: {
        name: attributes.name,
        type: 1,
        numUsers: attributes.numUsers,
        expDate: attributes.expDate
      }
    }, {
      include: DB.Organisation
    }).then(user => {
      return user.Organisation.update({ userId: user.id })
    }).then(org => {
      res.json(org);
    }).catch(next); 
  }).catch(next);

It gives me an error "column \"OrganisationId\" of relation \"Users\" does not exist". The insert query generated by SequelizeJS is:

INSERT INTO "Users" ("id","name","email","role","createdAt","updatedAt","OrganisationId") VALUES (DEFAULT,'vbvb','cdcd.pro@gmail.com',10,'2017-04-23 05:17:30.035 +00:00','2017-04-23 05:17:30.035 +00:00',20)

Obviously the "OrganisationId" does not exist in my table. The column name that exists is "organisationId". However, as per documentation for Sequelize its written that the default foreign key will be camelCased but in my case, its not camelCasing for Insert.



via Anil Konsal

No comments:

Post a Comment