mardi 8 août 2017

If statement runs but condition is not met

I'm using NodeJS, PassportJS, MySQL, and Sequalize(ORM for MySQL). This code is from my Passport.JS file. When a user registers on my website and the username or email is taken I will return an error. If both username and email can't be found in database a new create account will be created.

But the else statement to create a new account never runs. This error occurs when I create a new account with an untaken email and username.

Unhandled rejection TypeError: Cannot read property 'username' of undefined at null. (/home/ubuntu/workspace/Authentication.1/config/passport/passport.js:59:21) at tryCatcher (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/util.js:16:23) at Promise._settlePromiseFromHandler (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:512:31) at Promise._settlePromise (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:569:18) at Promise._settlePromise0 (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:614:10) at Promise._settlePromises (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:693:18) at Async._drainQueue (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/async.js:133:16) at Async._drainQueues (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/async.js:143:10) at Immediate.Async.drainQueues [as _onImmediate] (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/async.js:17:14) at processImmediate [as _immediateCallback] (timers.js:396:17)

// SELECT * FROM users WHERE username = username || email = ... 
User.findAll({
    where: {
      $or: [{username: username}, {email: req.body.email}]
    }
}).then(function(user){

// console.log('====================');
// console.log(user);
// console.log(user[0].username);  
// console.log(req.body.username);
// console.log(user[0].email);
// console.log(req.body.email);
// console.log('====================');

// If a user is returned from the database run this if statement
if(user != null) {
  // GETTING ERROR HERE. If username is already in database return err
  if(user[0].username == req.body.username) { **//THIS LINE CAUSE ERROR **
    console.log(user[0].username);  
    return done(null, false, console.log("USER TAKEN"),{message : 'That username is already taken'} );
  }

  // If email is already in database return err.
  else if(user[0].email == req.body.email) {
    return done(null, false, console.log("EMAIL TAKEN"),{message : 'That email is already taken'} );
  }  

}


else CREATE NEW ACCOUNT... // this never runs for some reason

Aucun commentaire:

Enregistrer un commentaire