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 badges2 Answers
Reset to default 7Apparently 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);
});
};