Home » Nodejs » is there a mongoose connect error callback

is there a mongoose connect error callback

Posted by: admin November 7, 2017 Leave a comment

Questions:

how can i set a callback for the error handling if mongoose isn’t able to connect to my DB?

i know of

connection.on('open', function () { ... });

but is there something like

connection.on('error', function (err) { ... });

?

Answers:

When you connect you can pick up the error in the callback:

mongoose.connect('mongodb://localhost/dbname', function(err) {
    if (err) throw err;
});

Questions:
Answers:

there many mongoose callback you can use,

// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {  
  console.log('Mongoose default connection open to ' + dbURI);
}); 

// If the connection throws an error
mongoose.connection.on('error',function (err) {  
  console.log('Mongoose default connection error: ' + err);
}); 

// When the connection is disconnected
mongoose.connection.on('disconnected', function () {  
  console.log('Mongoose default connection disconnected'); 
});

// If the Node process ends, close the Mongoose connection 
process.on('SIGINT', function() {  
  mongoose.connection.close(function () { 
    console.log('Mongoose default connection disconnected through app termination'); 
    process.exit(0); 
  }); 
}); 

more on: http://theholmesoffice.com/mongoose-connection-best-practice/

Questions:
Answers:

In case anyone happens upon this, the version of Mongoose I’m running (3.4) works as stated in the question. So the following can return an error.

connection.on('error', function (err) { ... });

Questions:
Answers:

Late answer, but if you want to keep the server running you can use this:

mongoose.connect('mongodb://localhost/dbname',function(err) {
    if (err)
        return console.error(err);
});