【问题标题】:timeoutError - MongoServerSelectionError: connect ECONNREFUSED ::1:27017 - [NodeJS + MongoDB]timeoutError - MongoServerSelectionError:连接 ECONNREFUSED ::1:27017 - [NodeJS + MongoDB]
【发布时间】:2021-11-20 11:31:10
【问题描述】:

免责声明:类似的主题没有为我的问题提供有效的解决方案!

  • 重新启动 MongoDB 服务器(发生错误时继续运行)
  • 在 windows 上使用 MongoDB 服务器作为服务(手动启动)
  • 通过 MongoDB Shell CLI 包建立连接,方法是在命令提示符下按 enter 建立默认连接 (mongodb://127.0.0.1:27017/directConnection=true&serverSelectionTimeoutMS=2000 )
  • 调用了 npm install 和 npm start(我的依赖在下面列出)
  • 检查 MongoDB 是否正在运行
  • 通过windows资源监视器查看27017端口被mongod.exe使用TCP占用,不受防火墙限制
  • 检查我没有使用可能干扰的 VPN 或代理连接。
  • 然后我打开了我正在收听的http://localhost:3000/ (app.listen(3000);)

但是,我仍然收到以下错误:

const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);                                     ^
 
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (\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 {
        _hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
        address: 'localhost:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 536295834,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (\node_modules\mongodb\lib\cmap\connect.js:293:20)
            at Socket.<anonymous> (\node_modules\mongodb\lib\cmap\connect.js:267:22)
            at Object.onceWrapper (node:events:510:26)
            at Socket.emit (node:events:390:28)
            at emitErrorNT (node:internal/streams/destroy:164:8)
            at emitErrorCloseNT (node:internal/streams/destroy:129:3)
            at processTicksAndRejections (node:internal/process/task_queues:83:21)
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}

我的依赖:

 "dependencies": {
    "ejs": "^3.1.6",
    "express": "^4.17.1",
    "mongodb": "^4.0.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }

仅供参考:Node.js v17.0.1

更新: 这是我的 database.js 文件

const mongodb = require('mongodb');

const MongoClient = mongodb.MongoClient;

let database;

async function connectToDatabase() {
  const client = await MongoClient.connect('mongodb://localhost:27017');
  database = client.db('file-demo');
}

function getDb() {
  if (!database) {
    throw { message: 'Database not connected!' };
  }
  return database;
}

module.exports = {
  connectToDatabase: connectToDatabase,
  getDb: getDb,
};

这是我的 app.js:

const path = require('path');

const express = require('express');

const userRoutes = require('./routes/users');
const db = require('./data/database');

const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(express.urlencoded({ extended: false }));
app.use(express.static('public'));

app.use(userRoutes);

db.connectToDatabase().then(function () {
  app.listen(3000);
});

【问题讨论】:

  • 该错误主要表示MongoDB服务器未启动提供的连接字符串uri不正确。您可能希望在帖子中包含连接代码。您是否能够使用mongoshmongo shell 或 Compass 等任何客户端工具连接到数据库服务器?
  • @prasad_ 我可以通过 MongoDB shell 与数据库交互(我通过 mongosh 成功使用了 CRUD 操作)。我用我用来建立连接的代码更新了我的帖子。
  • 尝试在 database.js 中将 'mongodb://localhost:27017' 更改为 localhost127.0.0.1
  • @prasad_ 非常感谢您,将其发布为答案,我将接受它以供将来参考。
  • 这是一个常见问题,并且已经有关于这个/类似问题的详细且解释清楚的答案。谢谢,编码愉快!

标签: node.js mongodb express mongo-shell


【解决方案1】:

正如@prasad_ 所指出的,将文件中的localhost 更改为127.0.0.1 会有所帮助,您将在该文件中建立与MongoDB 服务器的连接。 尽管它们应该被视为同义词,并且我能够排除一般问题(您可以在类似问题中找到答案),但这可能只是 chrome 的缓存问题,例如 here

【讨论】:

    【解决方案2】:

    对我来说,问题是我安装后没有运行 mongodb 服务。

    在 mac 上,运行:

    brew services start mongodb-community@5.0
    

    【讨论】:

    • 感谢您的回答,但是,如上所述,我确保它已启动并运行 :)
    猜你喜欢
    • 2023-04-09
    • 2021-12-18
    • 2020-04-10
    • 1970-01-01
    • 2022-12-10
    • 2022-12-30
    • 2021-09-12
    • 2022-11-09
    相关资源
    最近更新 更多