Why doesn't callback in db.collection().find().toArray(callback) get called if database connection is dropped?

I have this code:

db.collection('users').find({ active: true ).toArray(callback);

where db is an opened database connection to my local mongodb server. This works fine. But if I manually close my mongodb server while my app is still running, and then execute this line of code, callback is never executed, not even with error. Is this expected behaviour? What can I do to make my app react to dropped database connection?

Edit:

I tried this:

db.collection('users')
  .find({active: true}, function(err, cursor) {
    if (err) callback(err);
    else cursor.toArray(callback);
  });

Again, this works when connection is alive, but when connection is dropped, the anonymous callback function of find() is called with 'err' as null - and the callback of .toArray is not called at all. How do I rewrite my code so that I get an error if db connection is not alive?

In order to react to the dropped connection you can register an event listener for the close event, e.g.

db.on('close', function(err) {
    console.error('Connection to Mongo lost: %s', err);
});

You also have the option of adding an auto_reconnect directive to your Mongo connection so that it will try and reestablish the connection, e.g.

MongoClient.connect(mongoUri, { server: { auto_reconnect: true } }, handleConnect)

See the docs for more details of the options available for MongoClient.connect().

Regarding it not calling the .toArray() callback I would guess that the .collection() call failed due to connection represented by db no longer being active.