Jesse Fulton
Jesse Fulton

Reputation: 2218

Sequelize.js - model association during "create" or "build" call

I have a data model where an association/foreign key is required. Is there any way possible to enforce that constraint during model creation without getting into a chicken/egg situation?

Let's say I have a User class which requires at least one device to be associated with it. Likewise, the device must belong to a user. Something like this (untested code, don't mind syntax errors):

User = db.define("user", {
    name: Sequelize.STRING
})

Device = db.define("device", {
    uuid: Sequelize.STRING
})

User.hasMany(Device)

I want to ensure that when create is first called, that I have all Device information as well as all User information. Keeping with "fat models, skinny controllers" I'd like to put this into my models. Is it possible to do something like this?

user = User.create(
    name: "jesse"
    device:
        uuid: "84e824cb-bfae-4d95-a76d-51103c556057"
)

Can I override the create method? Or is there some type of before save event hook I can use?

Upvotes: 5

Views: 4324

Answers (1)

sdepold
sdepold

Reputation: 6241

The current master has support for hooks.

var User = sequelize.define('User', {
  username: DataTypes.STRING
}, {
  hooks: {
    beforeCreate: function(user, next) {
      makeYourCheck(function() {
        next("a string means that an error happened.")
      })
    }
  }
})

You can check the PR for further information: https://github.com/sequelize/sequelize/pull/894

Upvotes: 6

Related Questions