Mongoose连接MongoDB Atlas失败:非0.0.0.0 IP无法连接求助
Mongoose连接MongoDB Atlas失败:IP白名单问题(实际IP无法连接,0.0.0.0可正常连接)
我在尝试用Mongoose连接应用程序到MongoDB Atlas时失败,报错提示:
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist
将IP地址设置为0.0.0.0时可正常连接,但该方式仅适用于开发环境,我希望通过当前实际IP地址连接数据库。
连接代码
import mongoose from "mongoose" const Connection = async () => { const URL = `mongodb+srv://*****:*****@chittagongpestcontrol.hviumcx.mongodb.net/?retryWrites=true&w=majority`; try { await mongoose.connect(URL, { useNewUrlParser: true}) console.log('Databease connect successfully.') } catch(error) { console.log('Error while connecting with the database.',error); } } export default Connection;
完整错误信息
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://www.mongodb.com/docs/atlas/security-whitelist/ at _handleConnectionErrors (D:\Web\Node JS project\chittagongepestcontrol\server\node_modules\mongoose\lib\connection.js:792:11) at NativeConnection.openUri (D:\Web\Node JS project\chittagongepestcontrol\server\node_modules\mongoose\lib\connection.js:767:11) at async Connection (file:///D:/Web/Node%20JS%20project/chittagongepestcontrol/server/database/db.js:6:9) { reason: TopologyDescription { type: 'ReplicaSetNoPrimary', servers: Map(3) { 'ac-jodubob-shard-00-01.hviumcx.mongodb.net:27017' => [ServerDescription], 'ac-jodubob-shard-00-00.hviumcx.mongodb.net:27017' => [ServerDescription], 'ac-jodubob-shard-00-02.hviumcx.mongodb.net:27017' => [ServerDescription] }, stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, setName: 'atlas-bwulgu-shard-0', maxElectionId: null, maxSetVersion: null, commonWireVersion: 0, logicalSessionTimeoutMinutes: null }, code: undefined }
解决方法
1. 获取当前实际公网IP
- Linux/macOS终端执行:
curl ifconfig.me - Windows命令提示符执行:
nslookup myip.opendns.com resolver1.opendns.com - 也可通过本地网络设置或IP查询工具获取。
2. 在MongoDB Atlas添加IP白名单
- 登录Atlas控制台,进入目标集群页面;
- 左侧菜单选择「Network Access」;
- 点击「Add IP Address」;
- 填入刚获取的公网IP,按需设置过期时间;
- 点击「Confirm」保存。
3. 验证连接
- 重启Node.js应用,重新调用连接函数;
- 若仍报错,检查IP是否输入正确,或等待1-2分钟让设置生效(部分地区有延迟)。
额外提示
- 家庭宽带多为动态IP,IP会定期变化,需定期更新白名单;生产环境建议使用固定IP或云服务器;
- 检查本地防火墙、代理是否阻止了27017端口的访问;
- 确认连接URL中的用户名、密码、集群地址无拼写错误。
内容的提问来源于stack exchange,提问作者Ce Anuz
相关产品推荐
相关产品推荐

