Mongoose Model.find() hangs when not connected to database

I'm going through a few error scenarios, trying to understand how to handle those.

In the case where there is no database connection, a Mongoose Model.find(...) call seems to hang. Below the example code. I would have assumed that the callback is invoked with an err object, but it is not.

How can I prevent the model call to hang? Do I manually have to check the readyState each time I access a model?

// app.js
// Let's use a non-existing host so connecting fails:
// (callback is invoked with err object)
mongoose.connect('mongodb://localhostXXX/blog', function(err){ ... });

BlogPost  = mongoose.model('BlogPost', BlogPostSchema);

// api.js
exports.list_posts = function(req, res) {

    // Ready state is '0' = disconnected (since we used a wrong hostname)   
    console.log('DB ready state: ' + BlogPost.db.readyState);

    // This will not invoke the callback:
    BlogPost.find(function(err, threads) {
        // Never called...
    });
 }

It is not an answer, but hope it will help you to find solution. Had very similar issue with mongoose.createConnection while using passport module, found out that it works fine with mongoose.connect

Since you're already using an error handler in the connect call, a sensible thing would be to quit your app when the DB is not up, or activate some middleware that responds with a pretty 500 Internal Server Error.

Mongoose uses node-mongodb-native under the hood for connections to mongodb, you might find other useful connection options in there. :)

EDIT: try setting socketOptions.socketTimeoutMS. Apparently there is no default timeout set. See http://mongodb.github.com/node-mongodb-native/api-generated/server.html.

I don't have node on my work machine to try out the exact syntax for you, but you will probably have to use mongoose.Connection, which has an open() method that accepts options to pass through to node-mongodb-native. I don't think mongoose.connect() accepts these options, but I could be wrong.