NodeJS +猫鼬连接超时 [英] NodeJS + Mongoose timeout on connection
问题描述
因此,我读到NodeJS的 mongoose驱动程序会缓存查询,直到它连接到MongoDB(无超时)为止.但是,当数据库崩溃时,应该可以向用户发送消息.因此,让我们看一下这段NodeJS代码:
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
});
这可能挂在infintum.因此,解决此问题的一种方法是执行以下操作
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
});
问题是:这是一个好方法吗?内存泄漏(将查询挂到MongoDB上)如何处理?
And the question is: is this a good way? What about memory leaks (hanging queries to MongoDB)?
推荐答案
我通过在使用DB的每个路由器中添加一个额外的步骤来解决此问题.
I handled this problem by adding one additional step in each router where I use DB.
有点杂乱,但可以正常工作,并且100%无泄漏.
It's a little bit messy but it works and 100% no leaks.
类似这样的东西:
// 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如果您对解决方案有更好的了解,请告诉我.
PS If you know solution better, please let me know.
这篇关于NodeJS +猫鼬连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!