user3244377
user3244377

Reputation: 25

How to wait for a response from a mongo findOne query in a node/express app before using the response in following control flow

I am new to node, and also JavaScript callbacks.

I am trying to check if an account exists in mongo and then 'save it' if it doesn't and return an error if it does.

I am currently trying to figure this out outside of my express app. This is what i have..

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/main', function (err, db) {
    if(err) throw err;

    var query = { name : "www.website.com"}

    findOne(db, query, function (doc) {
        if(doc) {
            console.log('account exists');
        } else {
            console.log('good to go');
        }
        console.dir(doc);
    });

});

var findOne = function (db, query, callback) {
    db.collection('accounts').findOne(query, function (err, doc) {
        if(err) throw err;

        db.close();

        callback();
    });
}

with the console.dir(doc); above returning as undefined. How do I wait for the findOne to return before using the callback to console.log or save the account?

Upvotes: 1

Views: 6092

Answers (1)

Hector Correa
Hector Correa

Reputation: 26690

The reason you are getting undefined is because when you call your callback your are not passing it the doc. That line should look like callback(doc).

Here is an updated version of your code with a few suggestions:

MongoClient.connect('mongodb://localhost:27017/main', function (err, db) {

    if(err) throw err;

    var query = { name : "www.website.com"}

    findOne(db, query, function (err, doc) {
        if(err) {
            // something went wrong
            console.log(err);
            return;
        }

        if(doc) {
            console.log('account exists');
            console.dir(doc);
        } else {
            console.log('good to go');
        }

    });

});

var findOne = function (db, query, callback) {
    db.collection('accounts').findOne(query, function (err, doc) {

        db.close();

        if(err) {
            // don't use throw when in async code
            // the convention is to call your callback with the error
            // as the first argument (notice that I added an argument 
            // to the definition of your callback above)
            callback(err);
        }
        else {
            // call your callback with no error and the data
            callback(null, doc);
        }


    });
}

Upvotes: 3

Related Questions