I'am try created a project and use node.js + sequelize, the project have two model Fator and Sub_fator. They have a association 1:N, but when create fator, returned an erro:
Error: Fator.hasMany called with something that's not a subclass of Sequelize.Model
any sugestion for solved the error?
model Fator
'use strict';
const Sub_Fator = require('./sub_fator');
module.exports = (sequelize, DataTypes) => {
const Fator = sequelize.define('Fator', {
descricao: DataTypes.STRING
}, {});
Fator.associate = function(models) {
Fator.hasMany(Sub_Fator, {
foreignKey: 'fatorId',
as: 'fatores'
});
};
return Fator;
};
model Sub_fator
'use strict';
const Fator = require('./fator');
module.exports = (sequelize, DataTypes) => {
const Sub_Fator = sequelize.define('Sub_Fator', {
fatorId: DataTypes.INTEGER,
descricao: DataTypes.STRING
}, {});
Sub_Fator.associate = function(models) {
Sub_Fator.belongsTo(Fator, {
foreignKey: 'fatorId',
as: 'fatores'
});
};
return Sub_Fator;
};
//Removed this import because is not an object of Model it's a definition
module.exports = (sequelize, DataTypes) => {
const Fator = sequelize.define('Fator', {
descricao: DataTypes.STRING
}, {});
Fator.associate = function(models) {
Fator.hasMany(models.Sub_Fator, {//Change to this instead of Sub_Fator
foreignKey: 'fatorId',
as: 'fatores'
});
};
return Fator;
};
The reason is Because you define the model here, but then in your models/index.js or something like that you have to import it to generate an object model, this is just a model definition and it's not a SubClass of Sequelize.Model.
PS: Your index should something like this if you generated sequelize in your project:
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/server-config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
Tanks, solved my problem!