未知,未指明"错误"事件

时间:2016-12-29 05:38:24

标签: node.js mongoose

我遇到了这个错误"未捕获,未指定"错误"事件。 (参数不正确)"当试图使用邮递员登录时。请帮我弄清楚不正确的论点。

这是我的代码:

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

})

确切的错误: 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)

我正在使用:

  • 节点6.6.0
  • Mongoose 4.7.5
  • MongoDB 2.4.9

1 个答案:

答案 0 :(得分:2)

找到导致错误的原因,它来自我的其他代码,因为我使用的是箭头功能而不是匿名功能。

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