freeman29
freeman29

Reputation: 157

Uncaught, unspecified "error" event

I'm encountering this error "Uncaught, unspecified "error" event. (Incorrect arguments)" when trying to login using postman. Please help me figure out the incorrect arguments.

Here is my code:

router.post('/login', function(req, res) {
  User.findOne({
    username: req.body.username
  })
  .select('password')
  .exec(function(err, user) {

    console.log('err', err); // err is null

    if (err) throw err;

    if (!user) {
      res.status(404).send({message: 'User does not exist!'})
    }
    else if (user) {
      var validPassword = user.comparePassword(req.body.password);

      if (!validPassword) {
        res.status(401).send({message: 'Invalid Password'});
      }
      else {
        var token = createToken(user);
        res.json({
          success: true,
          message: 'Successfully login!',
          token: token
        })
      }
    }
  })

})

the exact error: events.js:165 throw err; ^ Error: Uncaught, unspecified "error" event. (Incorrect arguments) at Function.emit (events.js:163:17) at Immediate.<anonymous> (..../node_modules/mongoose/lib/query.js:2322:23) at runCallback (timers.js:574:20) at tryOnImmediate (timers.js:554:5) at processImmediate [as _immediateCallback] (timers.js:533:5)

I'm using:

Upvotes: 1

Views: 3473

Answers (1)

freeman29
freeman29

Reputation: 157

Found what cause the error, it's from my other code and it's because I'm using arrow function instead of anonymous function.

// don't use arrow function if you want to access the this keyword
UserSchema.methods.comparePassword = (password) => {
  var user = this;

  return bcrypt.compareSync(password, user.password);
}

// use anonymous function instead
UserSchema.methods.comparePassword = function(password) {
  var user = this;

  return bcrypt.compareSync(password, user.password);
}

Upvotes: 2

Related Questions