Mongodb无法连接到服务器错误

时间:2018-12-13 07:05:45

标签: javascript node.js mongodb express

我收到有关我运行“ nodemon index.js”后我的应用程序无法连接到mongo的错误:

{ MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND localhost localhost:27017]
at Pool.<anonymous> (/Users/Dakota/Projects/2018-Udemy-Bootcamp/node-mongo-project/todos_api/node_modules/mongodb-core/lib/topologies/server.js:564:11)
at emitOne (events.js:116:13)
at Pool.emit (events.js:211:7)
at Connection.<anonymous> (/Users/Dakota/Projects/2018-Udemy-Bootcamp/node-mongo-project/todos_api/node_modules/mongodb-core/lib/connection/pool.js:317:12)
at Object.onceWrapper (events.js:317:30)
at emitTwo (events.js:126:13)
at Connection.emit (events.js:214:7)
at Socket.<anonymous> (/Users/Dakota/Projects/2018-Udemy-Bootcamp/node-mongo-project/todos_api/node_modules/mongodb-core/lib/connection/connection.js:246:50)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }

我的代码如下:

let mongoose = require('mongoose');
let dbUrl = 'mongodb://localhost/todo-api';
mongoose.set('debug', true);

mongoose.Promise = Promise;

mongoose.connect(dbUrl, { useNewUrlParser: true }).then(() => {
  console.log("Database connection is active");
}).catch(err => {
  console.log(err);
});

module.exports.Todo = require('./todo');

我已经在终端上启动了mongod。

此问题发生在我的网络上的家中,但是如果我去街上的咖啡店,它将连接起来。我已经阅读了一些有关防火墙导致问题和IP地址的内容,并据我所知尝试调整了这两件事,但是我似乎仍然无法解决此问题。

对我如何解决此问题有任何见解?

1 个答案:

答案 0 :(得分:0)

首先,请检查您的mongodb服务是否正常运行。

此外,您可以将 localhost 替换为 127.0.0.1 ,如下所示:

// connect to database
mongoose.connect('mongodb://127.0.0.1/todo-api', { useNewUrlParser: true});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', function() {
  console.log(`MongoDB connected!`);
});

编辑:我从猫鼬文档中找到了this

  

MongoDB副本集依赖于能够可靠地确定每个成员的域名。在Linux和OSX上,MongoDB服务器使用hostname命令的输出来找出要报告给副本集的域名。如果您要连接到在其hostname报告为localhost的计算机上运行的远程MongoDB副本集,则会导致令人困惑的错误:

// Can get this error even if your connection string doesn't include
// `localhost` if `rs.conf()` reports that one replica set member has
// `localhost` as its host name.
failed to connect to server [localhost:27017] on first connect
  

如果遇到类似的错误,请使用mongo shell连接到副本集,然后运行rs.conf()命令以检查每个副本集成员的主机名。 Follow this page's instructions to change a replica set member's host name