How to handle mongo db unable to connect issue wit

2019-09-08 15:18发布

问题:

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?

回答1:

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.