Chris Paterson
Chris Paterson

Reputation: 1149

Why does "findOne" always tell me that err = null?

I have a simple query that always gives me a value of null for the err and I can't figure out why. Here is the code I have:

async.series([
    function(callback){
        User.findOne({ email :  req.body.email }, function(err, data) {
            console.log('email address' + req.body.email); // shows '[email protected]'
            console.log('err = ' + err); // always shows 'null'
            success = err ? false : true; 
            // do stuff
        });
        callback();
    },
    function(callback){
        var updateData = {
            reset_key: random
        };
        User.update({ email: req.body.email}, updateData, function(err,data) {
            callback();
        });
    }
], function(err){
    if(!err) {
        res.json({ success: success });
    }
});

Schema:

var userSchema = mongoose.Schema({
    firstname    : String,
    lastname     : String,
    email        : String,
    created : {
        type: Date,
        default: Date.now
    },
    reset_key : String 
});

The 2nd function call in the async is always successful as long as I enter an email address that already exists in the database. But, the first function call in async always tells me that err is null, regardless of whether or not I enter an email address that exists in the database. Why? What am I doing wrong?

Upvotes: 0

Views: 96

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123513

Each of the functions in the series will need to pass along any errs for the last function to receive them:

function(callback){
    User.findOne({ email :  req.body.email }, function(err, data) {
        // ...

        callback(err);
    });
}
function(callback){
    // ...
    User.update({ email: req.body.email}, updateData, function(err,data) {
        callback(err);
    });
}

Without providing the errs to the callbacks, async.series() isn't aware that any errs are occurring.

Upvotes: 1

John Petrone
John Petrone

Reputation: 27507

Finding no results with findOne is not an error condition, so err will not be set. If you are trying to determine if the query returned a result you cannot use err for that purpose.

Instead, you can check if data has anything in it - it will be empty if findOne() did not return any results.

Upvotes: 0

Related Questions