Reputation: 2278
I am building a user and role association using sequelizejs with postgres. Each user can have one role and each role belongs to many users.
I have setup the associations like this
global.db.User.belongsTo(global.db.Role, {foreignKey: 'role_id', as: 'Role'});
global.db.Role.hasMany(global.db.User, {foreignKey: 'role_id'});
Now, when I am setting up the objects and syncing sequelize like this in app.js it's not working:
var role = Role.build({ name: 'foo', permissions: 'bar'});
var user = User.build({username: 'sultansaadat', email: '[email protected]', password: 'sultan123', isActive: true});
db.sequelize.sync().complete(function (err) {
if (err) {
throw err
} else {
role.save();
user.setRole(role);
user.save();
}
});
I was expecting sequelize to behave like all normal ORMs do but I think there is something wrong here or either I'm doing something wrong.
Upvotes: 3
Views: 1620
Reputation: 28778
What exactly is not working?
node.js, and therefore also sequelize are async by nature. When you call role.save, that call returns before the database actually returns. You will have to wait for role to be saved and assigned an id, before you can assign it to a user.
role.save().done(function (err, role) {
user.save().done(function (err, user) {
user.setRole(role);
});
});
Upvotes: 5