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?

Answers


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);
        }


    });
}

Need Your Help

Command for loading jQuery on Google Chrome inspector?

jquery google-chrome web-inspector

I remember seeing that there was a specific command you could put on Google Chrome's inspector console for it to load jQuery and allow you to execute jQuery commands.

How to get accurate idft result from opencv?

python image opencv image-processing numpy

I use cv.dft to process an image and cv.idft to get it back following the tutorial here. However, the final image has very large gray value, which is much more than 255.