得到.findOrCreate()错误

时间:2013-09-25 11:01:53

标签: mysql node.js orm sequelize.js

我正在使用Sequelize作为ORM。这是我的用户模型:

###
    User model
###
User = exports.User =  globals.sequelize.define "User",
    username: globals.Sequelize.STRING
    email:
        type: globals.Sequelize.STRING
        validate:
            isEmail: true
    hash:     globals.Sequelize.STRING
    salt:     globals.Sequelize.STRING(512)
    fname:    globals.Sequelize.STRING
    lname:    globals.Sequelize.STRING
    country:  globals.Sequelize.STRING

我正在保存用户:

globals.models.User.findOrCreate
    username: "johny"
    password: "pass"
    email: "johny93[###]example.com"
.success (user, created)->
    console.log user.values
    res.send 200
.error ->
    console.log err # how to catch this?
    res.send 502

如果电子邮件有效(电子邮件:“johny93@example.com”),一切都很有效。但如果电子邮件验证失败(如上例所示),则会出现插入错误。如何捕获错误类型? .error方法无法获取任何错误参数。

3 个答案:

答案 0 :(得分:14)

 User.findOrCreate({
  where: {
    username: "johny",
    password: "pass",
    email: "johny93[###]example.com"
  },
  defaults: {
    //properties to be created 
  }
}).then(function(user){
  var created = user[1];
  user = user[0];
  console.log(user.values);
}).fail(function(err){
   console.log('Error occured', err);
});

https://github.com/sequelize/sequelize/wiki/Upgrading-to-2.0

编辑:正如@Domi所指出的,更好的方法是使用'spread'而不是'then'

User.findOrCreate({
  where: {
    username: "johny",
    password: "pass",
    email: "johny93[###]example.com"
  },
  defaults: {
    //properties to be created 
  }
}).spread(function(user, created){
  console.log(user.values);
}).fail(function(err){
   console.log('Error occured', err);
});

答案 1 :(得分:7)

sequelize会将错误作为参数传递给错误函数。

<强>的JavaScript

User.findOrCreate({username: "johny",password: "pass",email: "johny93[###]example.com"})
.success(function(user, created){
    console.log(user.values);
    res.send(200);
})
.error(function(err){
   console.log('Error occured' + err);
})

<强>的CoffeeScript

globals.models.User.findOrCreate
    username: "johny"
    password: "pass"
    email: "johny93[###]example.com"
.success (user, created)->
    console.log user.values
    res.send 200
.error (error)->
    console.log error # how to catch this?
    res.send 502

答案 2 :(得分:4)

Sequelize 2.0更改语法,现在是

User.findOrCreate({
  where: {
    username: 'johny',
    password: 'pass',
    email: 'johny93[###]example.com'
  }
}).then(function (user) {
  res.send(200);
}).catch(function (err) {
  console.log(err);
  res.send(502);
});