Is it possible to detect that the database is not running with Mongoose ?
You can tell if mongoose is already connected or not by simply checking
mongoose.connection.readyState
0 = no
1 = yes
I would recommend using the open
and error
events to check if you can connect to the database. This is a simple example used in all my projects to double check that I'm connected.
var mongoose = require('mongoose');
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
});
mongoose.connection.on('error', function (err) {
console.log('Could not connect to mongo server!');
console.log(err);
});
mongoose.connect('mongodb://localhost/mongodb');
The straight forward works fine for me:
mongoose.Connection.STATES.connected === mongoose.connection.readyState
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With