javascript - mongoose not supplying error in find function - Stack Overflow

In trying to construct a few statics with Mongoose, I can't seem to get access to the error argume

In trying to construct a few statics with Mongoose, I can't seem to get access to the error argument when calling find() or findOne(). Here's my static:

User.statics.authenticate = function(login, password, cb){
    return this.model('User').findOne({
        username: login, 
        password: password
    }, function(err, user){
        console.log("error", err);
        console.log("user", user);
    }).exec(cb);
};

I'm trying to call it with something like this:

exports.session = function(req, res){
    return User.authenticate(req.body.login, req.body.password, function(err, doc){
        console.log('err', err);
        console.log('doc', doc);
    });
};

In every circumstance, no matter the results of the findOne query, err is always null. Any idea on what's going on here? Maybe I just can't wrap my head around all of these callbacks...

In trying to construct a few statics with Mongoose, I can't seem to get access to the error argument when calling find() or findOne(). Here's my static:

User.statics.authenticate = function(login, password, cb){
    return this.model('User').findOne({
        username: login, 
        password: password
    }, function(err, user){
        console.log("error", err);
        console.log("user", user);
    }).exec(cb);
};

I'm trying to call it with something like this:

exports.session = function(req, res){
    return User.authenticate(req.body.login, req.body.password, function(err, doc){
        console.log('err', err);
        console.log('doc', doc);
    });
};

In every circumstance, no matter the results of the findOne query, err is always null. Any idea on what's going on here? Maybe I just can't wrap my head around all of these callbacks...

Share Improve this question asked Jul 4, 2012 at 0:48 bentobento 5,0268 gold badges43 silver badges60 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Apparently an empty query result is not actually an error, so that's the reason 'err' remains null despite not finding a result. So, you need to test if 'user' is null or not, and then create your own error.

I'm not sure it quite explains what you're seeing, but if you provide a callback function directly to findOne then you don't call exec. So your authenticate function should look like this instead:

User.statics.authenticate = function(login, password, cb){
    this.model('User').findOne({
        username: login, 
        password: password
    }, function(err, user){
        console.log("error", err);
        console.log("user", user);
        cb(err, user);
    });
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745401366a4626117.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信