I am working on one to many assocations with sequelize. Most tutorials and documentation shows examples when both models are defined in the same file. I currently have two files, first city.js:
const Promise = require('bluebird');
var Country = require('./country');
var City = sequelize.define("City", {
id: {
type: DataTypes.INTEGER,
field: 'id',
primaryKey: true,
autoIncrement: true
},...
}, {
freezeTableName: true,
timestamps: false
});
City.belongsTo(Country, {foreignKey : 'countryId', as: 'Country'});
Promise.promisifyAll(City);
module.exports = City;
And a second file country.js:
const Promise = require('bluebird');
var City = require('./city');
var Country = sequelize.define("Country", {
id: {
type: DataTypes.INTEGER,
field: 'id',
primaryKey: true,
autoIncrement: true
},
...
}, {
freezeTableName: true,
timestamps: false,
paranoid: false
});
Country.hasMany(City, {foreignKey : 'countryId', as: 'Cities'});
Promise.promisifyAll(Country);
module.exports = Country;
When I import both modules and try to instantiate object:
var City = require('../model/external/city');
var CountryRepository = require('../repository/external/countryRepository');
CountryRepository.findById(1).then(function(country) {
var city = City.build();
city.name = 'Paris';
city.setCountry(country);
console.log('OK');
});
I get the following error:
throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not an instance of Sequelize.Model')
Is the problem that models are promisified before they are exported from model or am I missing something?
Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.
I'm not sure what exactly is the problem with your code, would need to run it to be sure.
But as you were looking for an example, take a look at this example from Sequelize Github.
It declares models in different files and associate them in the index.js
.
Later you can reference your other model with a simple model
atribute model.Country
:
City.belongsTo(model.Country, {foreignKey : 'countryId', as: 'Country'});
For instance, user.js.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With