MongoServerSelectionError:连接 ECONNREFUSED ::1:27017

Sha*_*ush 7 mongodb node.js

我正在使用 Mongo 5.0.1 和 Node 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}`));
};
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误。

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
  }
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*ush 14

使用它作为你的 uri

  const uri = "mongodb://127.0.0.1:27017";
Run Code Online (Sandbox Code Playgroud)