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

使用Mongoose连接MongoDB Atlas失败的问题求助

MERN栈使用Mongoose连接MongoDB Atlas失败问题

我正在使用MERN栈开发应用,借助Mongoose连接MongoDB Atlas数据库,但始终无法成功建立连接。

我的代码

import {createRequire} from 'module';
const require = createRequire(import.meta.url);
require('dotenv').config();

const express = require('express');
const app = express();
 
app.use(express.json());

const PORT = 3000; 

const mongoose = require('mongoose');
const uri = {my db uri}

mongoose.connect(uri).then(() => {
    console.log('MongoDB Connected…')
}).catch(err => console.log(err));

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'Connection error:'));
db.once('open', () => {
  console.log("Connection is open...");
});

app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});

运行后出现的错误

PS {project location}\src\server> node server
Server listening on port 3000
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 ({project location}\node_modules\mongoose\lib\connection.js:875:11)
    at NativeConnection.openUri (C{project location}\node_modules\mongoose\lib\connection.js:826:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    servers: Map(3) {
      'ac-xpydyff-shard-00-01.rn4suxq.mongodb.net:27017' => [ServerDescription],
      'ac-xpydyff-shard-00-02.rn4suxq.mongodb.net:27017' => [ServerDescription],
      'ac-xpydyff-shard-00-00.rn4suxq.mongodb.net:27017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: 'atlas-f9m10v-shard-0',
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}
Connection error: MongoServerSelectionError: read ECONNRESET
    at EventTarget.<anonymous> ({project location}\node_modules\mongoose\node_modules\mongodb\lib\sdam\topology.js:276:34)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:807:20)
    at EventTarget.dispatchEvent (node:internal/event_target:742:26)
    at abortSignal (node:internal/abort_controller:369:10)
    at TimeoutController.abort (node:internal/abort_controller:391:5)
    at Timeout.<anonymous> ({project location}\node_modules\mongoose\node_modules\mongodb\lib\utils.js:1011:92)
    at listOnTimeout (node:internal/timers:573:17)
    at process.processTimers (node:internal/timers:514:7) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    servers: Map(3) {
      'ac-xpydyff-shard-00-01.rn4suxq.mongodb.net:27017' => [ServerDescription],
      'ac-xpydyff-shard-00-02.rn4suxq.mongodb.net:27017' => [ServerDescription],
      'ac-xpydyff-shard-00-00.rn4suxq.mongodb.net:27017' => [ServerDescription]
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: 'atlas-f9m10v-shard-0',
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {},
  [cause]: MongoNetworkError: read ECONNRESET
      at connectionFailureError ({project location}\node_modules\mongoose\node_modules\mongodb\lib\cmap\connect.js:379:20)
      at TLSSocket.<anonymous> ({project location}\node_modules\mongoose\node_modules\mongodb\lib\cmap\connect.js:285:22)
      at Object.onceWrapper (node:events:629:26)
      at TLSSocket.emit (node:events:514:28)
      at emitErrorNT (node:internal/streams/destroy:151:8)
      at emitErrorCloseNT (node:internal/streams/destroy:116:3)
      at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
    [Symbol(errorLabels)]: Set(1) { 'ResetPool' },
    [cause]: Error: read ECONNRESET
        at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) {
      errno: -4077,
      code: 'ECONNRESET',
      syscall: 'read'
    }
  }
}

已尝试的解决方法

  • 设置数据库允许所有IP访问
  • 尝试使用MongoDB原生连接方式
  • 移除所有CORS相关代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 17:04:59