hasMany called with something that's not an instance of Sequelize.Model

You don't need to declare the association on the Photo Model:

Foto.belongsTo(User, {foreignKey: 'userId'});

When you have a 1:N relation between models you only need to refer the id from the "1" model, on our case the User model, on the "N" model, Photos. So doing:

User.hasMany(Foto,{as: 'fotos', foreignKey: 'userId'})

Will create a column on your Foto table with name "userId" that refer to user table. On this way both models are associate as you want.


You can define relations for both models in one file. It doesn't throw any errors that way.

In your Foto.js, you can try:

...

Foto.belongsTo(User);
User.hasMany(Foto);

return Foto;

I had a similar problem. Sometimes it can be caused because in your index.js or app.js the files are loaded in a specific order, so for example if you have a relationship between A and B, A loads first and references B, and B in turn references A, the error will be thrown inside the B file because A has not been fully defined/executed yet.

The solution to this would be to remove all associations from the model files, and inside your app or index.js require them all, and then define their relationships.

Example

const entities = {
  A: require('./src/Entity/A'),
  B: require('./src/Entity/B'),
};
entities.A.belongsToMany(entities.B, {through: 'AB'});
entities.B.belongsToMany(entities.A, {through: 'AB'});