get .findOrCreate() error

后端 未结 3 1349
轻奢々
轻奢々 2021-01-18 04:03

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

###
    User model
###
User = exports.User =  globals.sequelize.define \"User\",
    usernam         


        
相关标签:
3条回答
  • 2021-01-18 04:32

    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
    
    0 讨论(0)
  • 2021-01-18 04:47

    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);
    });
    
    0 讨论(0)
  • 2021-01-18 04:53
     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);
    });
    
    0 讨论(0)
提交回复
热议问题