【问题标题】:MongoServerSelectionError: 连接 ECONNREFUSED ::1:27017
【发布时间】:2023-04-09 11:55:01
【问题描述】:

我正在使用 mongo 5.0.1 和节点 17.2.0 这是我的代码 如果我想使用此代码连接 atlas,它会成功运行,但是当我尝试连接本地数据库时,会出现此错误。

const { MongoClient } = require("mongodb");

async function main(){
    const uri = "mongodb://localhost:27017";

    const client = new MongoClient(uri);

    try{
        await client.connect();
        await listDatabases(client);
    } catch (e){
        console.error(e);
    } finally {
        await client.close();
    }
}
main().catch(console.error);

async function listDatabases(client) {
    databasesList = await client.db().admin().listDatabases();

    console.log("Databases:");
    databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};

这是我遇到的错误。

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (D:\web development\nodeDemo\node_modules\mongodb\lib\sdam\topology.js:330:38)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}

【问题讨论】:

  • 你确定本地的MongoDB已经启动了..?
  • 是的,mongodb 已启动

标签: node.js mongodb


【解决方案1】:

使用它作为你的 uri

  const uri = "mongodb://127.0.0.1:27017";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 2021-09-12
    • 1970-01-01
    • 2021-04-15
    • 2018-03-13
    • 2021-06-22
    • 2020-04-10
    相关资源
    最近更新 更多