7

我正在使用SequelizeORM。这是我的用户模型:

###
    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方法无法获取任何错误参数。

4

3 回答 3

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 指出的那样,更好的方法是使用“传播”而不是“那么”

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);
});
于 2014-10-13T06:46:52.253 回答
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);
})

咖啡脚本

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
于 2013-09-27T21:15:02.830 回答
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);
});
于 2015-02-10T17:16:32.340 回答