pat
pat

Reputation: 2790

Close erroneous mongoose connection

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.

Upvotes: 0

Views: 255

Answers (1)

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27809

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.

Upvotes: 1

Related Questions