NodeJS+Mongoose连接超时

NodeJS + Mongoose timeout on connection

本文关键字:超时 连接 NodeJS+Mongoose      更新时间:2023-09-26

所以我读过NodeJS的mongoose驱动程序缓存查询,直到它连接到MongoDB(没有超时)。但是当数据库崩溃时,应该可以向用户发送消息。让我们看看这个NodeJS代码:

Users.find({}, function(err, result) {
  // Do something with result and send response to the user
});

这可能是悬于内心的。因此,解决这个问题的一种方法是执行以下

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的查询)怎么办?

我通过在每个使用DB的路由器中添加一个额外的步骤来处理这个问题。

它有点乱,但它可以工作,100%没有泄漏。

类似这样的东西:

// 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如果您更了解解决方案,请告诉我。

我希望我能正确理解你的问题,我想你担心,因为猫鼬采取了乐观的模式,让你理所当然地认为它最终会连接,你担心当连接失败时,你将无法优雅地处理这种情况。

Connection.open()方法接受回调作为最后一个参数。如果无法打开连接,则将使用Error对象作为参数调用此回调。来自猫鼬的来源(端口和选项是可选的):

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

或者,您可以订阅连接的"错误"事件。它还接收错误对象作为参数。然而,只有当所有参数(和状态)都有效时,才会发出它,而每次都会调用回调,即使在实际连接尝试之前出现问题(例如连接不在readyState中),即使连接成功(在这种情况下,错误参数为null)。