首页 文章

错误:连接超时 - expressjs mongodb mongoose

提问于
浏览
0

一般来说,我是表达/节点和网络编程的新手 . 当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:\用户\肖恩\ OneDrive \网页\ 000 \ lasttry \ node_modules \ mongodb的\ lib中\ db.js:1798:14)在emitOne(事件.js:96:13)在Server的Server.emit(events.js:188:7) . (C:\ Users \ Sean \ OneDrive \ webpages \ 000 \ lasttry \ node_modules \ mongodb \ lib \ server.js:274:14)在Servers.emit的emitOne(events.js:96:13)处(events.js: 188:7)在游泳池 . (C:\ Users \ Sean \ OneDrive \ webpages \ 000 \ lasttry \ node_modules \ mongodb -core \ lib \ topologies \ server.js:335:12)在Pool.emit(events.js:96:13)的pool.emit( events.js:188:7)在Connection . 位于emitTwo的Connection.g(events.js:291:16)处的(C:\ Users \ Sean \ OneDrive \ webpages \ 000 \ lasttry \ node_modules \ mongodb-core \ lib \ connection \ pool.js:270:12) events.js:106:13)在Connection.emit(events.js:191:7)

2 回答

  • 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

  • 0
    • 检查mongod正在运行 .

    在shell中输入 mongo .

    • 为你添加 connectTimeoutMS=300000 参数 .

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

相关问题