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

时间:2016-07-20 16:50:20

标签: node.js mongodb heroku mlab

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

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);
  });
});

我的代码松散地基于this example。有人建议我在每次请求后打开一个与数据库的新连接,但是is not best practice从内部开始,MongoClient.connect正在管理一个池。我还尝试根据this更改一些选项。仍然没有运气。

1 个答案:

答案 0 :(得分:3)

这解决了我的问题:

let image = UIImage(named: "other_car")
let imageView = UIImageView(image: image)
cell.backgroundView = imageView

然后把它放在这里:

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