Charles
Charles

Reputation: 11778

Mongoose detect database not ready

Is it possible to detect that the database is not running with Mongoose ?

Upvotes: 10

Views: 10722

Answers (4)

Amit Portnoy
Amit Portnoy

Reputation: 6336

The straight forward works fine for me:

mongoose.Connection.STATES.connected === mongoose.connection.readyState

Upvotes: 10

timoxley
timoxley

Reputation: 5204

You can tell if mongoose is already connected or not by simply checking

mongoose.connection.readyState
0 = no
1 = yes

Upvotes: 21

Dan
Dan

Reputation: 1721

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');

Upvotes: 18

Gianfranco P
Gianfranco P

Reputation: 10794

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);
});

Upvotes: 4

Related Questions