mongoe's findOne method nether executes nor fails

Problem

I'm trying to retrieve data from mongodb through nodejs mnogdb-native driver. mongodconsole indicates that connection succeed. Unfortunately, after retrieving collection and logging message 'before findOne' to the console nothing happened. It's looks like thefindOne method never returns.

var mongo = require('mongodb'),
    config = require('./config');

var UserProvider = function() {
    this.db = new mongo.Db('chatbox', 
        new mongo.Server(config.mongoServer, config.mongoPort, {auto_reconnect: true}), {});
    this.db.open(function() {});
};

UserProvider.prototype.getCollection = function(callback) {
    this.db.collection('users', function(error, collection) {
    if (error) {
        callback(error);
    }
    else {
        callback(null, collection);
    }
    });
};

UserProvider.prototype.validateUser = function(username, password, callback) {
    this.getCollection(function(error, collection) {
        if (error) {
            console.log('error');
            callback(error);
        }
        else {
            console.log('before findOne');
            collection.findOne({login: username, password: password}, function(error, item){
                console.log('done');
                if (error) {
                    callback(error);
                }
                else {
                    callback(null, item != null);
                }
            });
        }   
    });
};

module.exports = UserProvider;

Can anybody point me to the probable problem point?

Problem courtesy of: koss

Solution

Take a look at the code that would use your code:

var myProvider = require('yourcode').UserProvider;

myProvider.validateUser('me','pwd', function(error, success) {
  console.log("Success: " + success);
});

When I get to myProvider.validateUser, am I guaranteed that this.db.open() has returned? Normally, this whole thing is sequential. But in Node.JS, that db.open() is not blocking. So the call goes out to the DB and then the code keeps running, so you actually have a race condition here.

Solution courtesy of: Gates VP

Discussion

A poke in the dark really - but try adding a console.log into the callback for db.open.

If that line does not show up before 'before findOne' then most likely the issues is simply that the DB connection is not open.

Discussion courtesy of: Jani Hartikainen

This recipe can be found in it's original form on Stack Over Flow.