问题
I am trying to connect to Atlas MongoDB with the following URI (provided by mongodb connection string )
module.exports = {
mongoURI:'mongodb+srv://<user>:<password>@cluster0-un6sk.mongodb.net/test?
retryWrites=true'
};
//connect to mongoose
mongoose
.connect(db)
.then( ()=>console.log('mongoDB connected'))
.catch(err => console.log(err));
I get the following error :
{ MongoNetworkError: connection 3 to cluster0-shard-00-00-un6sk.mongodb.net:27017 closed
at TLSSocket.<anonymous> (C:\Users\KARTIT Ismail\Desktop\devconnector\node_modules\mongodb-core\lib\connection\connection.js:352:9)
at Object.onceWrapper (events.js:273:13)
at TLSSocket.emit (events.js:182:13)
at _handle.close (net.js:606:12)
at TCP.done (_tls_wrap.js:386:7)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
回答1:
Make sure you have whitelisted your IP in the Atlas Control panel. You
can put 0.0.0.0
to allow access from any host.
Then you can have a connection string like below:
var connectionString= 'mongodb://<username>:<password>@<clustername>/<dbname>?ssl=true&replicaSet=<replica setname>&authSource=admin';
var db = mongoose.connect(connectionString).catch((error) => { console.log(error); });
回答2:
Whitelist the IP address, the best option allows access from any host, I believe everyone had installed mongoose, if not then use this command
npm i mongoose
First copy your application connection string from mongodb.com -> clusters->connect->connect your application
Now chose driver Node.js and version latest, now copy connection string.
Now connection.js
const mongoose = require('mongoose');
const conStr = 'mongodb+srv://lord:<password>@cluster5-eeev8.mongodb.net/test?retryWrites=true&w=majority'
const DB = conStr.replace(
'<password>',
myPass
);
const DB = conStr.replace(
'test',
myDatabaseName
);
//remember mongoose.connect() return promise
mongoose
.connect(DB, {
usedNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then((con) => {
console.log(con.connection);
console.log('DB connection successful');
});
回答3:
In order to connect to Atlas MongoDB you should configure IP whitelist. Go to MongoDB Atlas website, login. Then, from the Clusters view, select the Security tab, then IP Whitelist. You will see an IP address. Click "Edit" Button then "current IP address". Press OK. Then restart your server.
Useful link : https://docs.atlas.mongodb.com/security-whitelist/#add-whitelist-entries
回答4:
What version of mongoose are you using? Versions of mongoose less than version 5.0.15 doesn't appear to support the mongodb+srv://
server url.
The other common issue, is white listed IP addresses.
Source: Error at connecting to MongoDb Atlas Server
回答5:
Just whitelist the IP from the Atlas UI no need to restart the application.
来源:https://stackoverflow.com/questions/55971993/atlas-mongodb-connection