NodeJS + Mongoose timeout on connection NodeJS + Mongoose timeout on connection mongoose mongoose

NodeJS + Mongoose timeout on connection


I handled this problem by adding one additional step in each router where I use DB.

It's a little bit messy but it works and 100% no leaks.

Something like this:

// file: 'routes/api/v0/users.js'routervar User = require('../../../models/user').User,    rest = require('../../../controllers/api/v0/rest')(User),    checkDB = require('../../../middleware/checkDB');module.exports = function (app) {  app.get('/api/v0/users', checkDB, rest.get);  app.get('/api/v0/users/:id', checkDB, rest.getById);  app.post('/api/v0/users', checkDB, rest.post);  app.delete('/api/v0/users', checkDB, rest.deleteById);  app.put('/api/v0/users', checkDB, rest.putById);};// file: 'middleware/checkDB.js'var HttpError = require('../error').HttpError,    mongoose = require('../lib/mongoose');// method which checks is DB ready for work or notmodule.exports = function(req, res, next) {  if (mongoose.connection.readyState !== 1) {    return next(new HttpError(500, "DataBase disconnected"));  }  next();};

PS If you know solution better, please let me know.


I hope I'm understanding your question correctly, I think you're worried that, because mongoose takes an optimistic pattern and lets you take for granted that it will connect eventually, you're afraid you won't be able to gracefully handle the case when the connection fails.

The Connection.open() method accepts a callback as last argument. This callback will be called with an Error object as argument if the connection cannot be opened. From mongoose' source (port and options are optional):

Connection.prototype.open = function (host, database, port, options, callback)

Alternatively, you can subscribe to the Connection's "error" event. It also receives the error object as argument. However, it is only emitted if all arguments (and state) are valid, while the callback gets called every time, even if, for example, something goes wrong before the actual connection attempt (such as the connection not being in a readyState), and even if the connection is successful (in which case the error argument is null).