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