Question

When mongoose fails to connect to the DB, how do I properly end the script?

The following keeps running:

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/db', function(err){
    if (err) {
        console.log(err);
        mongoose.connection.close();
    }
});

I also tried mongoose.disconnect() with the same result.

The easiest way is obviously throw err; but this seems a brutal hammer solution to the problem.

Was it helpful?

Solution

If the connect function failed (i.e. err != null) that means the connection state is not open, therefore, you can't close or disconnect it.

To prove it to yourself, you can check the mongoose.connection.readyState (here are the available values).

May I suggest using mongoose.connection.on('error', cb); to better handle connection errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top