Question

Our Nodejs application uses Mongoose for MongoDB. Our application crashes when it unable to connect to MongoDB database. We are using MongoLab.

What are the best ways to handle database connect issue in Node JS application?

Was it helpful?

Solution

Just handle error with the associated events:

// If the connection throws an error
connection.on('error',function (err) {
  // Do something here
});

// When the connection is disconnected
connection.on('disconnected', function () {
  // Do something else here
});

And, of course, when running a query, it's very recommended to always check err parameter of the callback function before going any further.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top