问题
I am trying to perform a connection to mongodb using mongoose but it throws an error. Here is my code:
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));
Here is the error:
[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)]: {} }
回答1:
I got to solve the same problem: in the last three days my applications (node.js, express, mongoose, graphql) got connected to the mongoDB (in the cloud) whithout any problem, but today I got:
Error: MongoNetworkError: failed to connect to server [cluster0-shard-00-00-cpkkj.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to cluster0-shard-00-00-cpkkj.mongodb.net:27017 closed]
I verified the IP of my PC and that's it: it has changed and is not more the same IP I added to the Whitelist, so I added the new one and the problem was solved.
回答2:
If you would like to enable any host connection access, you can set to the whitelist in atlas configuration the following IP address:
- 0.0.0.0
Then, even when your IP address suddenly changes, you might still connect.
来源:https://stackoverflow.com/questions/56828919/mongodb-atlas-connection-error-failed-to-connect-to-server