Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize one to many assocation in multiple files

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?

like image 610
Ronald Tucker Avatar asked Apr 26 '16 17:04

Ronald Tucker


People also ask

How do I use association in Sequelize?

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.


1 Answers

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.

like image 76
Denis C de Azevedo Avatar answered Oct 20 '22 18:10

Denis C de Azevedo