MongoDB连接MongoLab在Heroku上的NodeJS中超时

时间:2023-01-02 02:37:29

At first everything works, and I can successfully store data by posting to the /upload route. But after 120 seconds of inactivity, the timeout event fires, and future attempts to store data fail. However the callback isn't called, so there is no "Unable to insert..." message at the log.

一开始一切正常,我可以通过发布到/ upload路由成功存储数据。但是在120秒不活动之后,超时事件将触发,并且将来存储数据的尝试将失败。但是,不调用回调,因此日志中没有“无法插入...”消息。

var express = require('express');
var bodyParser = require('body-parser');
var winston = require('winston');
var config = require('./config');
var MongoClient = require('mongodb').MongoClient;

var app = express();

app.use(bodyParser.json());

app.post('/upload', function (req, res) {
  req.json({status: 'recieved'});
  req.app.locals.db.collection('data').insertOne(req.body, function(err, result) {
    if (err === null) {
      winston.info('Successfully inserted', {data: req.body});
    } else {
      winston.warn('Unable to insert', {cause: err});
    }
  });
});

const options = {
  server: {
    socketOptions: {
      keepAlive: 1,
      autoReconnect: true,
      connectTimeoutMS: 5000
    }
  }
};

MongoClient.connect(config.databaseURI, function(err, db) {
  if (err !== null) {
    winston.error('Could not connect to database', {cause: err});
    return;
  }

  db.on('timeout', function (err) {
    winston.error('Mongo timed out', {cause: err});
  });

  app.locals.db = db;
  app.listen(config.port, function() {
    winston.info('Listening on port %d', config.port);
  });
});

I based my code loosely off of this example. It has been suggested to me that I open a new connection to the DB after every request, but this is not best practice since internally, MongoClient.connect is managing a pool. I also tried changing some of the options according to this. Still no luck.

我的代码松散地偏离了这个例子。有人建议我在每次请求后打开一个新的数据库连接,但这不是最好的做法,因为在内部,MongoClient.connect正在管理一个池。我也尝试根据这个改变一些选项。仍然没有运气。

1 个解决方案

#1


2  

This solved the problem for me:

这解决了我的问题:

var options = { 
  server: { 
    socketOptions: { 
      keepAlive: 300000, connectTimeoutMS: 30000 
    } 
  }, 
  replset: { 
    socketOptions: { 
      keepAlive: 300000, 
      connectTimeoutMS : 30000 
    } 
  } 
};

Then put it in here:

然后把它放在这里:

if(process.env.MONGODB_URI) {
  mongoose.connect(process.env.MONGODB_URI, options);
} else {

  // Connect to local database

}

#1


2  

This solved the problem for me:

这解决了我的问题:

var options = { 
  server: { 
    socketOptions: { 
      keepAlive: 300000, connectTimeoutMS: 30000 
    } 
  }, 
  replset: { 
    socketOptions: { 
      keepAlive: 300000, 
      connectTimeoutMS : 30000 
    } 
  } 
};

Then put it in here:

然后把它放在这里:

if(process.env.MONGODB_URI) {
  mongoose.connect(process.env.MONGODB_URI, options);
} else {

  // Connect to local database

}