1

I have two models defined like this:

user.js

var sequelize = require('../database.js').sequelize,
    Sequelize = require('../database.js').Sequelize,
    userAttributes = require('./userAttributes.js');

User = sequelize.define('user', {},{
    classMethods: {
        createRider: function(params) {
            var reqs = ['name', 'phone', 'fbprofile'],
                values = [],
                newUser;
            reqs.forEach((req) => {
                var value = params[req];
            });

            //Here I want to use the userAttributes-object.

            return newUser;
        }
    }
});

module.exports = User;

userAttributes.js

var sequelize = require('../database.js').sequelize,
    Sequelize = require('../database.js').Sequelize,
    User = require('./user.js');

UserAttribute = sequelize.define('userAttributes', {
    name:       Sequelize.STRING,
    value:      Sequelize.STRING,
});
UserAttribute.belongsTo(User);

module.exports = UserAttribute;

in user User.addRider I want to add some records to UserAttributes, so I want to inclued that model in user. In userAttributes, I need to require Users to define it as a belongsTo. This doesn't seem to work. How can I solve this?

Himmators
  • 14,278
  • 36
  • 132
  • 223
  • The problem stems from putting the requires at the top of the file (if you insist on having circular file dependencies). Put the User require after the UserAttribute assignment happens, and the UserAttribute require after User gets assigned - that should work despite not being very clean. – Catalyst Jun 22 '16 at 09:09
  • how should I do this without circular dependencies? – Himmators Jun 22 '16 at 10:23
  • saying "insist" may have been a little unfair - Sequelize does seem to want things this way here. Why not put the UserAttribute definition in the same file as User, just under the User definition? That should work since UserAttributes will be defined by the time the createRider function gets called. – Catalyst Jun 26 '16 at 06:49

1 Answers1

0

You can use a single file which imports all models and associates them after all models have been imported. This way, you do not need any circular references.

The second most popular answer in this question describes how to do it: How to organize a node app that uses sequelize?.

Community
  • 1
  • 1
Steffen Langer
  • 1,141
  • 1
  • 12
  • 16