So I've read that mongoose driver for NodeJS caches queries until it connects to MongoDB (no timeouts). But when the db crashes it should be possible to send a message to the user. So let's look at this NodeJS code:
Users.find({}, function(err, result) {
// Do something with result and send response to the user
});
This may be hanging at infintum. So one way to fix this problem is to do the following
var timeout = setTimeout(function() {
// whem we hit timeout, respond to the user with appropriate message
}, 10000);
Users.find({}, function(err, result) {
clearTimeout(timeout); // forget about error
// Do something with result and send response to the user
});
And the question is: is this a good way? What about memory leaks (hanging queries to MongoDB)?
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'
router
var 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 not
module.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With