node.js MongoDB 连接错误:MongoTimeoutError:服务器选择在 30000 毫秒后超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/59162342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB connection error: MongoTimeoutError: Server selection timed out after 30000 ms
提问by Arvind Krmar
I am trying to create a fullstack app reading the following tutorial:
我正在尝试创建一个完整的应用程序,阅读以下教程:
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)
MongoDB 连接错误:MongoTimeoutError:服务器选择在 Timeout._onTimeout (C:\RND\fullstack_app\backend\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9) 在 30000 毫秒后超时(内部/ 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: 服务器选择在 30000 毫秒后超时在 Timeout._onTimeout (C:\RND\fullstack_app\backend\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9) 在 listOnTimeout (internal/timers.js:531:17) 在 processTimers (internal/timers.js:475:7)
My code at server.js is as follows:
我在 server.js 上的代码如下:
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?
有什么建议?
回答by kunal usapkar
just go to mongodb atlas admin panel.Go in security tab>Network Access> Then whitelist your IP by adding it
只需转到 mongodb atlas 管理面板。进入安全选项卡>网络访问>然后通过添加将您的 IP 列入白名单
See this image to locate the particular menu
Note:Check your IP on google then add it
注意:在谷歌上检查你的IP然后添加它
回答by Smartniggs
Ensure that the "<" and ">" are removed when you replace the user and password fields. This worked for me
确保在替换用户和密码字段时删除“<”和“>”。这对我有用
回答by Odubola Oluwatimilehin
Sometimes this error occur due to the IP Address given access to to our database.
有时会发生此错误是由于 IP 地址允许访问我们的数据库。
Mind you, your application can be working well then come up with such error. Anytime this happen, most times your IP addresses has changed, which is not on the whitelist of address allowed.
请注意,您的应用程序可以正常运行,然后出现此类错误。每当发生这种情况时,大多数情况下您的 IP 地址已更改,这不在允许的地址白名单中。
All you have to do is go update the whitelist with your current IP addresses
您所要做的就是使用您当前的 IP 地址更新白名单
回答by Matheus
You can remove{ useUnifiedTopology: true }flag and reinstall mongoose dependecy! it worked for me.
您可以删除{ useUnifiedTopology: true }标志并重新安装猫鼬依赖!它对我有用。
回答by Kushal
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.
将您的连接 IP 地址列入白名单。Atlas 只允许客户端从项目白名单中的条目连接到集群。项目白名单不同于 API 白名单,后者限制 API 访问特定 IP 或 CIDR 地址。
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.
如果 Atlas 在 Setup Connection Security 步骤中指示您已经在集群中配置了白名单条目,则可以跳过此步骤。要管理 IP 白名单,请参阅将条目添加到白名单。
If the whitelist is empty, Atlas prompts you to add an IP address to the project's whitelist. You can either:
如果白名单为空,Atlas 会提示您将 IP 地址添加到项目的白名单中。您可以:
Click Add Your Current IP Address to whitelist your current IP address.
单击添加您当前的 IP 地址以将您当前的 IP 地址列入白名单。
Click Add a Different IP Address to add a single IP address or a CIDR-notated range of addresses.
单击添加不同的 IP 地址以添加单个 IP 地址或 CIDR 标记的地址范围。
For Atlas clusters deployed on Amazon Web Services (AWS) and using VPC Peering, you can add a Security Group associated with the peer VPC.
对于部署在 Amazon Web Services (AWS) 上并使用 VPC 对等互连的 Atlas 集群,您可以添加与对等 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.
您可以为新添加的 IP 地址或 CIDR 范围提供可选描述。单击添加 IP 地址将地址添加到白名单。
回答by Bathiya Seneviratne
I got the same error. These are the steps I followed for resolve it
我得到了同样的错误。这些是我为解决它而遵循的步骤
- Go to the security tab -> Network Access ->Then whitelist your IP
- Then go to the security tab -> Database Access ->and delete your current user.
- Create a new user by providing new username and password.
- Provide that newly created username and password in the .envfile or mongoose.connectmethod
- 转到安全选项卡 -> 网络访问 ->然后将您的 IP 列入白名单
- 然后转到安全选项卡 -> 数据库访问 ->并删除您当前的用户。
- 通过提供新的用户名和密码来创建一个新用户。
- 提供对新创建的用户名和密码.ENV文件或mongoose.connect方法
After these steps it worked as usual. hope this will help you guys.
在这些步骤之后,它照常工作。希望这会帮助你们。
回答by Daniel Danielecki
Are you using any Antivirus, Firewall, VPN or on the restricted network (e.g. work/commercial Wi-Fi/LAN connection)? Then try to turn it off/reconnect to a different network. Some IPs/connections might be blocked by the administrator of a network that you're using or simply antivirus might have firewall policies. Even though if you have 0.0.0.0in your IP Addressat the MongoDB Atlas.
您是否使用任何防病毒软件、防火墙、VPN 或受限网络(例如工作/商业 Wi-Fi/LAN 连接)?然后尝试将其关闭/重新连接到其他网络。您正在使用的网络管理员可能会阻止某些 IP/连接,或者只是防病毒软件可能具有防火墙策略。即使0.0.0.0您IP Address在 MongoDB Atlas 中拥有。
回答by rekwet
I had the same issue. I could connect from MongoDB Compass or my Node app using the connection strings Atlas gave me. I resolved it by adding my IP Address into the Whitelist in Atlas.
我遇到过同样的问题。我可以使用 Atlas 给我的连接字符串从 MongoDB Compass 或我的 Node 应用程序进行连接。我通过将我的 IP 地址添加到 Atlas 的白名单中来解决它。
回答by Lalit Sharma
To anyone still struggling through this issue. I resolved this issue by setting all the parameters like username, password and dbName in mongoose options itself.
对于仍在努力解决这个问题的任何人。我通过在 mongoose 选项本身中设置所有参数(如用户名、密码和 dbName)解决了这个问题。
Earlier the code was like this. (When I was getting the error).
之前的代码是这样的。(当我收到错误时)。
import mongoose from "mongoose";
mongoose.Promise = require("bluebird");
let dbName = process.env.DB_NAME;
const dbAddress = process.env.DB_HOST;
const dbPort = process.env.DB_PORT;
if(!dbName || !dbAddress || !dbPort){
throw new Error("Mongo error unable to configuredatabase");
}
let options = {
useNewUrlParser: true,
useUnifiedTopology: true,
user:process.env.DB_USER,
pass: process.env.DB_PASS
};
mongoose.connect(`mongodb://${dbAddress}:${dbPort}/${dbName}`, options).catch(err => {
if (err.message.indexOf("ECONNREFUSED") !== -1) {
console.error("Error: The server was not able to reach MongoDB. Maybe it's not running?");
process.exit(1);
} else {
throw err;
}
});
Note that url in mongo connect. mongodb://${dbAddress}:${dbPort}/${dbName}.
请注意 mongo 中的 url 连接。mongodb://${dbAddress}:${dbPort}/${dbName}.
New code without error.
新代码没有错误。
import mongoose from "mongoose";
mongoose.Promise = require("bluebird");
let dbName = process.env.DB_NAME;
const dbAddress = process.env.DB_HOST;
const dbPort = process.env.DB_PORT;
// console.log("process.env", process.env)
if(!dbName || !dbAddress || !dbPort){
throw new Error("Mongo error unable to configuredatabase");
}
let options = {
useNewUrlParser: true,
useUnifiedTopology: true,
user:process.env.DB_USER,
pass: process.env.DB_PASS,
dbName: dbName
};
mongoose.connect(`mongodb://${dbAddress}:${dbPort}`, options).catch(err => {
if (err.message.indexOf("ECONNREFUSED") !== -1) {
console.error("Error: The server was not able to reach MongoDB. Maybe it's not running?");
process.exit(1);
} else {
throw err;
}
});
Note the options and the url.
请注意选项和网址。
This is my local env. Not production env.
这是我的本地环境。不是生产环境。
Hope It'll be helpful.
希望它会有所帮助。
回答by dkovskij
try to specify the node driver, version 2,2,12 in cluster --> connect --> connect your application. new string must be with mongodb://. use this string to connect. do not forget to enter a password
尝试在集群中指定节点驱动程序版本 2、2、12 --> 连接 --> 连接您的应用程序。新字符串必须使用 mongodb://。使用此字符串进行连接。不要忘记输入密码

