Sequelize one to many assocation in multiple files

匿名 (未验证) 提交于 2019-12-03 01:05:01

问题:

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?

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!