質問

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.

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top