You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vercel部署的Node.js后端无法连接MongoDB Atlas问题求助

问题:Vercel部署的Node.js后端无法连接MongoDB Atlas

我有一个React/Node.js项目,仅将后端(server文件夹)部署到Vercel。后端已在Vercel上正常托管,通过server.js中的简单API测试可验证:

$ curl https://<mylink>/api/test
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    29  100    29    0     0    149      0 --:--:-- --:--:-- --:--:--   151
{"message":"API is working!"}

但当尝试发起任何与MongoDB数据库交互的请求时均失败,响应如下:

$ curl https://<mylink>/api/db-debug
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    85  100    85    0     0    432      0 --:--:-- --:--:-- --:--:--   435
{"message":"Database debug error","error":"Connection not established: Disconnected"}

我已完成以下MongoDB Atlas与Vercel的集成步骤:

  • 创建了拥有readWriteAnyDatabase@admin角色的用户vercel-admin-user
  • 在MongoDB Atlas的网络访问白名单中添加了0.0.0.0/0,允许任意IP连接
  • 在Vercel环境变量中正确配置了MONGO_URI

该API在本地运行完全正常:

$ curl http://localhost:5000/api/db-test
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    75  100    75    0     0   2277      0 --:--:-- --:--:-- --:--:--  2343
{"message":"The MONGODB Database connection is working!","result":{"ok":1}}

Vercel日志信息:
当调用部署后端的/api/db-test端点时,Vercel日志中出现以下错误:

Database connection error: TypeError: Cannot read properties of undefined (reading 'admin')
    at /var/task/server/server.js:121:49
    ...
Error connecting to MongoDB: 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/

/api/db-test端点的代码如下:

app.get('/api/db-test', async (req, res) => {
  try {
    const result = await mongoose.connection.db.admin().ping();
    res.json({ message: 'The MONGODB Database connection is working!', result });
  } catch (error) {
    console.error('Database connection error:', error);
    res.status(500).json({ message: 'Database connection error', error });
  }
});

内容的提问来源于stack exchange,提问作者Ehab Abdalla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 08:27:20