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

Viewed 5085

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...
    });
 }
3 Answers
Related