A is not associated to B

Viewed 1660

Looked on the internet about similar questions/errors, none of them helped me...

Unhandled rejection SequelizeEagerLoadingError: Task is not associated to User!

My users route

router.get('', function (req, res) {
  models.User.findAll({
    include: [
      {
        model: models.Task,
        as: 'tasks'
      }
    ]
  }).then(function (users) {
    res.send(users);
  });
});

User model

'use strict';

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    email: DataTypes.STRING
  }, {
    underscored: true
  });

  User.associations = function (models) {
    User.hasMany(models.Task, { as: 'tasks' });
  };

  return User;
};

Task model

'use strict';

module.exports = (sequelize, DataTypes) => {
  const Task = sequelize.define('Task', {
    name: DataTypes.STRING
  }, {
    underscored: true
  });

  Task.associations = function (models) {
    Task.belongsTo(models.User);
  };

  return Task;
};

I associate them both, and made a bidirectional relationship..

1 Answers

As you are using the finder function for association with as option, Sequelize cannot find that alias, as it is not defined explicitly anywhere. Please try this one:

User.associations = function (models) {
  User.hasMany(models.Task, { as: 'tasks' });
};

Hope this helps.

Related