MongoDB connection error: MongoTimeoutError: Server selection timed out after 30000 ms

笑着哭i 提交于 2020-01-10 19:46:30

问题


I am trying to create a fullstack app reading the following tutorial:

https://medium.com/javascript-in-plain-english/full-stack-mongodb-react-node-js-express-js-in-one-simple-app-6cc8ed6de274

I followed all steps and then tried to run:

node server.js

But I got the following error:

MongoDB connection error: MongoTimeoutError: Server selection timed out after 30000 ms at Timeout._onTimeout (C:\RND\fullstack_app\backend\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9) at listOnTimeout (internal/timers.js:531:17) at processTimers (internal/timers.js:475:7) { name: 'MongoTimeoutError', reason: Error: connect ETIMEDOUT 99.80.11.208:27017 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1128:14) { name: 'MongoNetworkError', [Symbol(mongoErrorContextSymbol)]: {} }, [Symbol(mongoErrorContextSymbol)]: {} } (node:42892) UnhandledPromiseRejectionWarning: MongoTimeoutError: Server selection timed out after 30000 ms at Timeout._onTimeout (C:\RND\fullstack_app\backend\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9) at listOnTimeout (internal/timers.js:531:17) at processTimers (internal/timers.js:475:7)

My code at server.js is as follows:

const mongoose = require('mongoose');
const router = express.Router();

// this is our MongoDB database
const dbRoute =
    'mongodb+srv://user:<password>@cluster0-3zrv8.mongodb.net/test?retryWrites=true&w=majority';

mongoose.Promise = global.Promise;

// connects our back end code with the database
mongoose.connect(dbRoute, 
    {   useNewUrlParser: true,
        useUnifiedTopology: true
    });

let db = mongoose.connection;

db.once('open', () => console.log('connected to the database'));

Any suggestions?


回答1:


just go to mongodb atlas admin panel.Go in security tab>Network Access> Then whitelist your IP by adding it

See this image to locate the particular menu

Note:Check your IP on google then add it




回答2:


Whitelist your connection IP address. Atlas only allows client connections to the cluster from entries in the project’s whitelist. The project whitelist is distinct from the API whitelist, which restricts API access to specific IP or CIDR addresses.

NOTE

You can skip this step if Atlas indicates in the Setup Connection Security step that you have already configured a whitelist entry in your cluster. To manage the IP whitelist, see Add Entries to the Whitelist.

If the whitelist is empty, Atlas prompts you to add an IP address to the project’s whitelist. You can either:

Click Add Your Current IP Address to whitelist your current IP address.

Click Add a Different IP Address to add a single IP address or a CIDR-notated range of addresses.

For Atlas clusters deployed on Amazon Web Services (AWS) and using VPC Peering, you can add a Security Group associated with the peer VPC.

You can provide an optional description for the newly added IP address or CIDR range. Click Add IP Address to add the address to the whitelist.




回答3:


You can try:

// Import express
let express = require('express');
// Import Body parser
let bodyParser = require('body-parser');
// Import Mongoose
let mongoose = require('mongoose');
// Initialize the app
let app = express();

// Import routes
let apiRoutes = require("./api-routes");
// Configure bodyparser to handle post requests
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

// Connect to Mongoose and set connection variable
mongoose.connect('mongodb://XXXX:XXXX@cluster0-shard-00-00-ov74c.mongodb.net:27017,cluster0-shard-00-01-ov74c.mongodb.net:27017,cluster0-shard-00-02-ov74c.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority', {useNewUrlParser: true})
    .then(()=>console.log("DB server connect"))
    .catch(e => console.log("DB error", e));


var db = mongoose.connection;

// Added check for DB connection

if(!db)
    console.log("Error connecting db")
else
    console.log("Db connected successfully")

// Setup server port
var port = process.env.PORT || 8080;

// Send message for default URL
app.get('/', (req, res) => res.send('Hello World with Express'));

// Use Api routes in the App
app.use('/api', apiRoutes);
// Launch app to listen to specified port
app.listen(port, function () {
    console.log("Running RestHub on port " + port);
});



回答4:


i was has this problem, to me the solution was check if my ip be configured correctly and before confirm in this screen

enter image description here




回答5:


You can remove { useUnifiedTopology: true } flag and reinstall mongoose dependecy! it worked for me.




回答6:


Please Check your Password, Username OR IP configuration. Mostly "Server selection timed out after 30000 ms at Timeout._onTimeout" comes whenever your above things are not matched with your server configuration.




回答7:


I am able to solve the issue. Everything was fine, but the firewall was blocking access to port 27017. connectivity can be tested at http://portquiz.net:27017/ or using telnet to the endpoint which can be retrieved from clusters->Metrics.

Thanks, everybody for the suggestions




回答8:


Try to make new User in Database Access with the default Authentication Method which is "SCRAM". Then make a new Cluster for that. It worked for me! My server.js file

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

//const uri = process.env.ATLAS_URI;
mongoose.createConnection("mongodb+srv://u1:u1@cluster0-u3zl8.mongodb.net/test", { userNewParser: true, useCreateIndex: true,  useUnifiedTopology: true}
    );

const connection = mongoose.connection;
connection.once('once', () => {
    console.log(`MongoDB databse connection established successfully`);
})

app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});



回答9:


What is your mongoose version? because there is an issue with a certain mongoose version. Please visit this link for more details "https://github.com/Automattic/mongoose/issues/8180". Anyway, I was facing the same issue but after using an older version (5.5.2), it worked for me. Please give a try and let me know what happened.



来源:https://stackoverflow.com/questions/59162342/mongodb-connection-error-mongotimeouterror-server-selection-timed-out-after-30

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!