Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose detect database not ready

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

like image 352
Charles Avatar asked Jul 18 '12 09:07

Charles


3 Answers

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

mongoose.connection.readyState
0 = no
1 = yes
like image 79
timoxley Avatar answered Oct 19 '22 22:10

timoxley


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');
like image 28
Dan Avatar answered Oct 19 '22 23:10

Dan


The straight forward works fine for me:

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

like image 39
Amit Portnoy Avatar answered Oct 20 '22 00:10

Amit Portnoy