MongoServerSelectionError:连接 ECONNREFUSED ::1:27017

She*_*edi 2 mongodb node.js mongo-shell nodemon

当我尝试使用 Mongoose 将我的应用程序与数据库连接时遇到问题。已经尝试过以下我在谷歌上找到的解决方案:

在Windows上重新启动MongoDB服务,使用位于MongoDB的bin文件上的cmd手动打开数据库,但我无法解决它。谁能帮我?

这是我的index.js

const { MongoClient } = require('mongodb')
const url = 'mongodb://localhost:27017';
const database = 'e-comm'
const client = new MongoClient(url);

async function getData()
{
    let result = await client.connect();
    let db = result.db(database);
    let collection = db.collection('products');
    let response =  await collection.find({}).toArray();
    console.log(response);
}
getData();

Run Code Online (Sandbox Code Playgroud)

并抛出错误

C:\Users\HP\new node\node_modules\mongodb\lib\sdam\topology.js:292
                const timeoutError = new error_1.MongoServerSelectionError(`Server selection
 timed out after ${serverSelectionTimeoutMS} ms`, this.description);
                                     ^

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (C:\Users\HP\new node\node_modules\mongodb\lib\sdam\topology.js:29
2:38)
    at listOnTimeout (node:internal/timers:564:17)
    at process.processTimers (node:internal/timers:507:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) {
      'localhost:27017' => ServerDescription {
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 32573830,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\HP\new node\node_modules\mongodb\lib\cmap\co
nnect.js:387:20)
            at Socket.<anonymous> (C:\Users\HP\new node\node_modules\mongodb\lib\cmap\connec
t.js:310:22)
            at Object.onceWrapper (node:events:628:26)
            at Socket.emit (node:events:513: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) {
          cause: Error: connect ECONNREFUSED ::1:27017
              at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
            errno: -4078,
            code: 'ECONNREFUSED',
            syscall: 'connect',
            address: '::1',
            port: 27017
          },
          [Symbol(errorLabels)]: Set(1) { 'ResetPool' }
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}

Node.js v18.12.1
Run Code Online (Sandbox Code Playgroud)

Joe*_*Joe 5

默认情况下 mongodb侦听IP4 localhost 127.0.0.1

该错误消息表明您正在尝试连接到 IP6 本地主机::1

这可能是因为您正在使用主机名localhost并且您的本地操作系统正在解析为 IP6 地址 ::1

要解决此问题,您需要让 mongoose 连接到 mongod 正在侦听的相同地址和端口,因此您需要:

a) 更改 mongod 配置,使其::1除了监听或代替监听127.0.0.1。参见net.ipv6

b) 更改 mongoose 配置以使用 IP 地址而不是主机名:const url = 'mongodb://127.0.0.1:27017';