错误:连接超时 - expressjs mongodb mongoose

时间:2017-02-11 15:35:31

标签: mongodb express mongoose

我一般都是表达/节点和网络编程的新手。当mongoose的mongodb连接超时时,处理此错误的最佳方法是什么,这就是我连接的方式:

mongoose.connect(config.mongoUrl);

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'error connecting with mongodb database:'));
db.once('open', function() {
  console.log('connected to mongodb database');
});

当我的服务器运行时超时时出现错误:

与mongodb数据库连接时出错:错误:连接超时     在Db。 (C:\用户\肖恩\ OneDrive \网页\ 000 \ lasttry \ node_modules \猫鼬\ lib中\驱动\节点mongodb的天然\ connection.js:169:17)     在emitTwo(events.js:106:13)     在Db.emit(events.js:191:7)     在Server.listener(C:\ Users \ Sean \ OneDrive \ webpages \ 000 \ lasttry \ node_modules \ mongodb \ lib \ db.js:1798:14)     在emitOne(events.js:96:13)     在Server.emit(events.js:188:7)     在服务器上。 (C:\用户\肖恩\ OneDrive \网页\ 000 \ lasttry \ node_modules \ mongodb的\ lib中\ server.js:274:14)     在emitOne(events.js:96:13)     在Server.emit(events.js:188:7)     在游泳池。 (C:\用户\肖恩\ OneDrive \网页\ 000 \ lasttry \ node_modules \ mongodb的核\ lib中\拓扑\ server.js:335:12)     在emitOne(events.js:96:13)     在Pool.emit(events.js:188:7)     在Connection。 (C:\用户\肖恩\ OneDrive \网页\ 000 \ lasttry \ node_modules \ mongodb的核\ lib中\连接\ pool.js:270:12)     在Connection.g(events.js:291:16)     在emitTwo(events.js:106:13)     在Connection.emit(events.js:191:7)

2 个答案:

答案 0 :(得分:5)

如何断开连接只需重新连接到mongo。见下文:

mongoose.connect(config.mongoUrl);

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'error connecting with mongodb database:'));

db.once('open', function() {
  console.log('connected to mongodb database');
});    

db.on('disconnected', function () {
   //Reconnect on timeout
   mongoose.connect(config.mongoUrl);
   db = mongoose.connection;
});

您还可以在连接上设置超时值。

mongoose.connect(url, { server: { socketOptions: { connectTimeoutMS: 1000 }}}, function(err) { ... });

此外,请确保mongo仍在您的计算机上运行。连接超时可能意味着mongo没有运行。

参考:Another stack overflow question

答案 1 :(得分:0)

  1. 检查mongod是否正在运行。

    在shell中输入mongo

  2. 为您添加connectTimeoutMS=300000参数。

    uri看起来像mongodb://localhost/collectionName?connectTimeoutMS=300000

相关问题