mongoose没有返回记录

时间:2016-11-02 13:32:17

标签: javascript mongodb mongoose

我正在构建一个简单的登录应用程序,并且发生了一件奇怪的事情。我设置的方式是:

  • 正在从客户端发送用户名和密码
  • 在服务器上我正在搜索基于仅用户名的记录,在回调中我正在比较密码(我使用bcryptjs进行散列和比较密码)

我遇到的问题是,如果我从客户端发送错误的密码,findOne回调不会给我记录或错误,这很奇怪,因为应该在回调中检查密码,以及查询密码首先没有提供。 代码如下:

router.post('/', function(req, res, next){
        User.findOne({username: req.body.username}, 'username password _id', function(err, user){
        if (err) {
            return next(err);
        }
        if(user) {
            bcrypt.compare(req.body.password, user.password, function(err, valid) {
                if (err) {
                    return next(err);
                }
                if(!valid) {
                    res.send({error: 'wrong password'});
                } else {
                    var token = jwt.encode({id: user._id}, config.secret);
                    res.send(201, token);
                }
            })
        } else {// this block is executed if the wrong password is sent, but it shouldn't, it should be if the username is wrong, right?
            res.send({error: 'wrong username'});
        }

    })
})

基本上,如果发送了错误的密码,usernull并且代码的else块被执行,密码永远不会被比较。

1 个答案:

答案 0 :(得分:1)

通常findOne不会抛出error,而是在找不到null时返回match

您可以使用like这个:

User.findOne( {...}, function (err, result) {
    if (err) { return next(err) }
    if (!result) {
       // do stuff here
    }
}
相关问题