get .findOrCreate() error

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

I'm using Sequelize as ORM. Here's my user model:

###     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 

I'm saving user:

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 

If email is valid (email: "johny93@example.com"), everything works great. But if email fails validation (as in the example above), I get an insertion error. How to catch error type? .error method can't get any error parameters.

回答1:

sequelize will pass the error as the paramater to the error function.

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); }) 

CoffeScript:

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:

 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

EDIT: as @Domi pointed out, better way is to use 'spread' instead of '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); }); 


回答3:

Sequelize 2.0 changes syntax and would now be

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); }); 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!