slifty slifty - 3 months ago 50
Node.js Question

Creating instance with an association in Sequelize

Using Sequelize, I've created two models:

User
and
Login
.

Users can have more than one Login, but a login must have exactly one user, which means a Login cannot be saved without a User ID.

How do I
.create
a Login with a User association all in one swoop?

Current Code (Doesn't Work)

// Set up the models
var User = sequelize.define('User', {});
var Login = sequelize.define('Login', {});
Login.belongsTo(User, {
onDelete: 'cascade',
foreignKey: {
field: 'userId',
allowNull: false,
}
});

// Create the instances
var user = User.create().then(function() {

// THIS IS WHERE I WOULD LIKE TO SET THE ASSOCIATION
var login = Login.create({
userId: user.get('id')
});

)};


The above results in
SequelizeValidationError: notNull Violation: UserId cannot be null

Answer

In your .then, the callback receives the model instance created by the previous call. You need to specify the argument inside the callback function.

var user = User.create().then(function(user) {

  // THIS IS WHERE I WOULD LIKE TO SET THE ASSOCIATION
  var login = Login.create({
    userId: user.get('id')
  });

  return login

}).then(function(login) {
    // all creation are complete. do something.
});

Also something important I would like to point out is your missing var statements! Those are important but not related to this question. See Declaring variables without var keyword