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

后端无法连接MongoDB Atlas,请求排查代码问题

问题描述

尝试通过后端连接MongoDB Atlas,实现前端候选人数据存储功能,但后端运行时无法连接数据库。服务器可正常监听端口,但数据库连接失败,报错信息及server.js代码如下:

server.js代码

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();

const app = express();
const port = 5000;

// 连接MongoDB
mongoose.connect(process.env.DATABASE,{
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => console.log('DB Connected'));

// 导入Candidate模型
const Candidate = require('./candidate');

// 使用中间件
app.use(bodyParser.json());
app.use(cors());

// 添加候选人的路由
app.post('/api/addcandidate', async (req, res) => {
  const { candidate_name, party_name, imageURL } = req.body;
  try {
    const candidate = new Candidate({
      candidate_name,
      party_name,
      imageURL
    });
    await candidate.save();
    res.status(201).json({ message: 'Candidate added successfully' });
  } catch (error) {
    res.status(500).json({ message: 'Failed to add candidate' });
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

错误信息

Server listening on port 5000
C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongoose\lib\connection.js:847
  const serverSelectionError = new ServerSelectionError();
                               ^

MongooseServerSelectionError: 无法连接到MongoDB Atlas集群中的任何服务器。常见原因之一是你尝试从未加入白名单的IP地址访问数据库。请确保当前IP地址已添加到Atlas集群的IP白名单中。
    at NativeConnection.Connection.openUri (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongoose\lib\connection.js:847:32)
    at C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongoose\lib\index.js:351:10
    at C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongoose\lib\index.js:1149:10)
    at Mongoose.connect (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongoose\lib\index.js:350:20)
    at Object.<anonymous> (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\server.js:11:10)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    setName: null,
    maxSetVersion: null,
    maxElectionId: null,
    servers: Map(3) {
      'ac-96s78iv-shard-00-00.1fwqsln.mongodb.net:27017' => ServerDescription {
        address: 'ac-96s78iv-shard-00-00.1fwqsln.mongodb.net:27017',
        error: MongoNetworkError: connection <monitor> to 3.212.187.25:27017 closed
            at Connection.handleIssue (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongodb\lib\cmap\connection.js:131:15)
            at TLSSocket.<anonymous> (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongodb\lib\cmap\connection.js:64:35)
            at TLSSocket.emit (node:events:527:28)
            at node:net:709:12
            at TCP.done (node:_tls_wrap:582:7),
        roundTripTime: -1,
        lastUpdateTime: 263109128,
        lastWriteDate: null,
        opTime: null,
        type: 'Unknown',
        topologyVersion: undefined,
        minWireVersion: 0,
        maxWireVersion: 0,
        hosts: [],
        passives: [],
        arbiters: [],
        tags: []
      },
      'ac-96s78iv-shard-00-01.1fwqsln.mongodb.net:27017' => ServerDescription {
        address: 'ac-96s78iv-shard-00-01.1fwqsln.mongodb.net:27017',
        error: MongoNetworkError: connection <monitor> to 3.212.158.17:27017 closed
            at Connection.handleIssue (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongodb\lib\cmap\connection.js:131:15)
            at TLSSocket.<anonymous> (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongodb\lib\cmap\connection.js:64:35)
            at TLSSocket.emit (node:events:527:28)
            at node:net:709:12
            at TCP.done (node:_tls_wrap:582:7),
        roundTripTime: -1,
        lastUpdateTime: 263108910,
        lastWriteDate: null,
        opTime: null,
        type: 'Unknown',
        topologyVersion: undefined,
        minWireVersion: 0,
        maxWireVersion: 0,
        hosts: [],
        passives: [],
        arbiters: [],
        tags: []
      },
      'ac-96s78iv-shard-00-02.1fwqsln.mongodb.net:27017' => ServerDescription {
        address: 'ac-96s78iv-shard-00-02.1fwqsln.mongodb.net:27017',
        error: MongoNetworkError: connection <monitor> to 3.210.79.179:27017 closed
            at Connection.handleIssue (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongodb\lib\cmap\connection.js:131:15)
            at TLSSocket.<anonymous> (C:\Users\Heet\Desktop\PROGRAMS\add-candidate-main\add-candidate-main\backend\node_modules\mongodb\lib\cmap\connection.js:64:35)
            at TLSSocket.emit (node:events:527:28)
            at node:net:709:12
            at TCP.done (node:_tls_wrap:582:7),
        roundTripTime: -1,
        lastUpdateTime: 263108869,
        lastWriteDate: null,
        opTime: null,
        type: 'Unknown',
        topologyVersion: undefined,
        minWireVersion: 0,
        maxWireVersion: 0,
        hosts: [],
        passives: [],
        arbiters: [],
        tags: []
      }
    },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
}
[nodemon] app crashed - waiting for file changes before starting...

解决步骤

  • 配置IP白名单:登录MongoDB Atlas控制台,进入目标集群的「网络访问」页面,将当前主机的IP地址添加到白名单;开发环境可临时添加0.0.0.0/0允许所有IP访问(生产环境禁用此操作)。
  • 校验连接字符串:确认.env文件中的DATABASE值为正确的Atlas连接字符串,需包含合法的用户名、密码、集群地址,且使用srv协议(格式示例:mongodb+srv://<用户名>:<密码>@集群地址/数据库名?retryWrites=true&w=majority)。
  • 添加连接错误捕获:完善数据库连接代码的错误处理逻辑,方便定位问题:
mongoose.connect(process.env.DATABASE,{
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log('DB Connected'))
.catch(err => console.error('DB Connection Error:', err));
  • 检查依赖兼容性:确保mongoose与mongodb依赖版本匹配,避免因版本冲突导致连接失败。

内容的提问来源于stack exchange,提问作者MR_DEVLOPER 01

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:57:05