Mongoose detect database not ready

javascript, mongodb, mongoose, node.js

Solution

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

Problem

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

Original source