ecdani ecdani - 1 year ago 70
Javascript Question

Retrieve MongoDB result outside callback function scope

I'm trying to get the document retrieved by MongoClient findOne method (in r parameter) outside the scope of callback function. How can i achieve that?

Maybe my approach to the usage of MongoDB driver for Node.js is not appropiate.

function loadUser(name) {
var result = {};

function connection(err, db) {
assert.equal(null, err);

function callback(err, r) {
assert.equal(null, err);
db.close();
result = r; // This does not work
}
db.collection('users').findOne({'user.name':name}, callback);
}
MongoClient.connect(url, connection);
return result;
}

Answer Source

The way you're doing it, result will not be the correct object because it's returned before MongoDB can find it and the value assigned.

You should do something like:

function loadUser(name, cb) {

    function connection(err, db) {
        assert.equal(null, err);

        function callback(err, r) {
            assert.equal(null, err);
            db.close();
            cb(err, user)
        }
        db.collection('users').findOne({'user.name':name}, callback);
    }
    MongoClient.connect(url, connection);
    return;
}

And the usage of loadUser would be:

loadUser("example", function(err, user){
   console.log(user);
   //Now do what you need with user
});

Also notice that if you are always searching for users, it would be better to just open the connection once, and close it once application is terminated.