Associations - Automatic methods not working
See original GitHub issueI’m new to Node.js, Express and Sequelize (v5.8.6). In my project, I have defined a hasMany-belongsTo relationship. Location is the source model and User is the target model. After having defined the association, I am supposed to have access to the magic methods (getUsers(), setUsers(), etc.). But when I try to Location.getUsers(), I get the error:
TypeError: Location.getUsers is not a function
I’ve used Sequelize-CLI to generate my models and migrations. My files look like this:
models/index.js
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'production';
const config = require(__dirname + '/../config/config.js')[env];
const db = {};
var sequelize = new Sequelize(config.database, config.username, config.password, config);
fs
.readdirSync(__dirname)
.filter(file => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(file => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
models/location.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const Location = sequelize.define('Location', {
name: {
allowNull: false,
type: DataTypes.STRING
},
}, {
sequelize,
modelName: 'location',
underscored: true,
});
Location.associate = function(models) {
Location.hasMany(models.User);
};
return Location;
};
models/user.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
email: {
allowNull: false,
type: DataTypes.STRING
},
location_id: {
type: DataTypes.INTEGER
},
}, {
sequelize,
modelName: 'user',
underscored: true
});
User.associate = function(models) {
User.belongsTo(models.Location);
};
return User;
};
When I try doing console.log(Location.associations)
from my location.js file, I just get {}
but when I try to log it in my index.js file, I get {Users: Users}
but I still can’t access Location.getUsers()
Any help would be appreciated. Thanks in advance!
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:7 (1 by maintainers)
nah, in my case the method was just named wrong lol You’re probably right that that was @ashishsanjayrao 's issue though
in my case, I was adding “_” in the model’s name and that causes to this error, just pay attention to your model’s name