Andreas Andreas - 14 days ago 5
Node.js Question

Adding table column with foreign key constraint using migrations in Sequelize

I'm trying to add a user_id column with a foreign key contraint to a Todo-table in Node Express using Sequelize with Postgresql.
I get an error message saying "Unhandled rejection SequelizeDatabaseError: column "UserId" does not exist". As you can see there is both "userId" and "UserId" in the SELECT query.
"Unhandled rejection SequelizeDatabaseError: column "UserId" does not exist"

The SELECT query is built by a simple Todo.findAll().
I believe it's something wrong in how I create the foreign key contraints in the migration file 20161116202040-add-user-id-to-todos.js

module.exports = {
up: function (queryInterface, Sequelize) {
return queryInterface.addColumn(
'Todos',
'userId', {
type: Sequelize.INTEGER,
references: {
model: 'Users',
key: 'id'}})},


The models/user.js looks like this:

module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
email: DataTypes.STRING,
password: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.Todo);}}});
return User;};


the models/todo.js looks like this:

module.exports = function(sequelize, DataTypes) {
var Todo = sequelize.define('Todo', {
name: DataTypes.STRING,
userId: DataTypes.INTEGER
},{
classMethods: {
associate: function(models) {
Todo.belongsTo(models.User); }}});
return Todo;};

Answer

Sequelize has a way to associate the related models via the model name.

So for example

var User = sequelize.define('user', { ... });
var Todo = sequelize.define('todo', { ... });

Todo.belongsTo(User);

// Will create/use `userId` in Todo table

But in your case where you have the table name as capitals :

var User = sequelize.define('User', { ... });
var Todo = sequelize.define('Todo', { ... });

Todo.belongsTo(User);

// Will create/use `UserId` in Todo table

So in your case you can either rename userId to UserId or specify explicitly the foreignKey like

Todo.belongsTo(models.User, { foreignKey: "userId" });
Comments