2

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;};

1 Answer 1

5

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" });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I figured it out. It seems to me that you'd also have to add foreignKey: "userId" to the User.hasMany call right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.