MongoError:连接0到localhost:27017超时

Pra*_*sha 7 mongoose mongodb node.js

events.js:141
      throw er; // Unhandled 'error' event
MongoError: connection 0 to localhost:27017 timed out
at Function.MongoError.create (/home/ubuntu/scripts/node_modules/mongodb-core/lib/error.js:29:11)
    at Socket.<anonymous> (/home/ubuntu/scripts/node_modules/mongodb-core/lib/connection/connection.js:184:20)
    at Socket.g (events.js:260:16)
    at emitNone (events.js:67:13)
    at Socket.emit (events.js:166:7)
    at Socket._onTimeout (net.js:318:8)
    at _runOnTimeout (timers.js:524:11)
    at _makeTimerTimeout (timers.js:515:3)
    at Timer.unrefTimeout (timers.js:584:5)
Run Code Online (Sandbox Code Playgroud)

好吧,在连接过程中没有错误,但是当尝试保存一些模型/集合时,它会运行一段时间,然后它会抛出此错误.BTW我还有另一个节点进程连接到同一个mongodb服务器.任何帮助都非常感谢.

Pra*_*sha 11

const mongoose = require('mongoose');
const option = {
    socketTimeoutMS: 30000,
    keepAlive: true,
    reconnectTries: 30000
};

const mongoURI = process.env.MONGODB_URI;
mongoose.connect(mongoURI, option).then(function(){
    //connected successfully
}, function(err) {
    //err handle
});
Run Code Online (Sandbox Code Playgroud)

  • 它们在mongoose 5.x中已弃用,您现在可以将它们放在选项映射的顶层.`const options = {keepAlive:300000,connectTimeoutMS:30000};` (2认同)

Shr*_*tra 5

您的查询需要很长时间。并且 mongo 本身有一个默认的超时设置。所以它超时,如果查询花费的时间超过超时时间。