MongoDB Atlas连接错误“无法连接到服务器...”

时间:2019-07-01 00:18:01

标签: node.js mongodb mongoose connection

我正在尝试使用猫鼬执行与mongodb的连接,但会引发错误。 这是我的代码:

mongoose.connect("mongodb+srv://username:password@cluster0-bocic.mongodb.net/test?retryWrites=true", {useNewUrlParser: true})
    .then(()=>console.log("Database connected..."))
    .catch(err=>console.log(err));

这是错误:

[0] { MongoNetworkError: failed to connect to server [cluster0-shard-00-01-bocic
.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to cluster
0-shard-00-01-bocic.mongodb.net:27017 closed]
[0]     at Pool.<anonymous> (C:\Users\Med\Desktop\jutsuapp\myapp\node_modules\mo
ngodb-core\lib\topologies\server.js:431:11)
[0]     at Pool.emit (events.js:182:13)
[0]     at connect (C:\Users\Med\Desktop\jutsuapp\myapp\node_modules\mongodb-cor
e\lib\connection\pool.js:557:14)
[0]     at callback (C:\Users\Med\Desktop\jutsuapp\myapp\node_modules\mongodb-co
re\lib\connection\connect.js:109:5)
[0]     at runCommand (C:\Users\Med\Desktop\jutsuapp\myapp\node_modules\mongodb-
core\lib\connection\connect.js:129:7)
[0]     at Connection.errorHandler (C:\Users\Med\Desktop\jutsuapp\myapp\node_mod
ules\mongodb-core\lib\connection\connect.js:321:5)
[0]     at Object.onceWrapper (events.js:273:13)
[0]     at Connection.emit (events.js:182:13)
[0]     at TLSSocket.<anonymous> (C:\Users\Med\Desktop\jutsuapp\myapp\node_modul
es\mongodb-core\lib\connection\connection.js:350:12)
[0]     at Object.onceWrapper (events.js:273:13)
[0]     at TLSSocket.emit (events.js:182:13)
[0]     at _handle.close (net.js:610:12)
[0]     at TCP.done (_tls_wrap.js:386:7)
[0]   name: 'MongoNetworkError',
[0]   errorLabels: [ 'TransientTransactionError' ],
[0]   [Symbol(mongoErrorContextSymbol)]: {} }

2 个答案:

答案 0 :(得分:3)

如果要启用任何主机连接访问权限,则可以将以下IP地址设置为图集配置中的白名单:

  • 0.0.0.0

然后,即使您的IP地址突然更改,您仍然可以连接。

答案 1 :(得分:1)

我必须解决相同的问题:在最近三天内,我的应用程序(node.js,express,mongoose,graphql)连接到mongoDB(在云中)时没有任何问题,但是今天我得到了:

错误:MongoNetworkError:首次连接时无法连接到服务器[cluster0-shard-00-00-cpkkj.mongodb.net:27017]的连接[MongoNetworkError:到cluster0-shard-00-00-cpkkj的连接5 .mongodb.net:27017已关闭]

我验证了PC的IP,就是这样:它已更改,并且与我添加到白名单中的IP不再相同,因此我添加了新IP,问题得以解决。