Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize.js - Asynchronous validators

Is it possible to have an asynchronous validator using Sequelize.js? I want to check for the existence of an association before saving a model. Something like this:

User = db.define("user", {
    name: Sequelize.STRING
},
{
    validate:
        hasDevice: ->
            @getDevices().success (devices) ->
                throw Exception if (devices.length < 1)
              return
})

# .... Device is just another model

User.hasMany(Device)

Or is there a way to force that check to run synchronously? (not ideal)

like image 697
Jesse Fulton Avatar asked Sep 13 '26 19:09

Jesse Fulton


1 Answers

you can use asynchronous validations in v2.0.0. It works like this:

var Model = sequelize.define('Model', {
  attr: Sequelize.STRING
}, {
  validate: {
    hasAssociation: function(next) {
      functionThatChecksTheAssociation(function(ok) {
        if (ok) {
          next()
        } else {
          next('Ooops. Something is wrong!')
        }
      })
    }
  }
})
like image 58
sdepold Avatar answered Sep 16 '26 12:09

sdepold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!