0

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. It works great. But when the connection error, the request waits for response for a long time. Is there any way to timeout? is there any difference between connnection timeout and socket timeout?
As far as I know, a socket timeout implies a connection timeout. You can define the connection timeout by passing it as a option when calling connect : mongoose.connect(url, { server: { socketOptions: { connectTimeoutMS: 1000 }}}, function(err) { ... });
Thanks. But MongoLab blogs talk about connection timeout and socket timeout separately blog.mongolab.com/2013/10/do-you-want-a-timeout

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.