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
The straight forward works fine for me:
mongoose.Connection.STATES.connected === mongoose.connection.readyState
Apparently Mongoose it self doesn't throw any exceptions.
So you can use the Mongo DB Native NodeJS Driver:
So here's what you can do:
var mongoose = require('mongoose');
var Db = require('mongodb').Db,
Server = require('mongodb').Server;
console.log(">> Connecting to mongodb on 127.0.0.1:27017");
var db = new Db('test', new Server("127.0.0.1", 27017, {}));
db.open(function(err, db) {
console.log(">> Opening collection test");
try {
db.collection('test', function(err, collection) {
console.log("dropped: ");
console.dir(collection);
});
}
catch (err) {
if (!db) {
throw('MongoDB server connection error!');
}
else {
throw err;
}
}
});
process.on('uncaughtException', function(err) {
console.log(err);
});
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');