【问题标题】:My npm keeps crashing. What am i doing wrong?我的 npm 不断崩溃。我究竟做错了什么?
【发布时间】:2023-01-19 15:39:09
【问题描述】:

代码:

const mongodb = require('mongodb');

const MongoClient = mongodb.MongoClient;

let dataBase;

async function connect() {
   const client = await MongoClient.connect('mongodb://localhost:27017'); 
   dataBase = client.db('blog'); 
};

function getDb() {
    if (!dataBase) {
        throw { message: "Database connection not established" };
    }
    return dataBase;
};

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

我不断收到此消息:

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\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\sdam\topology.js:305:38)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502: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: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 85766126,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:382:20)
            at Socket.<anonymous> (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:302:22)
            at Object.onceWrapper (node:events:642:26)
            at Socket.emit (node:events:527: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) { 
          [Symbol(errorLabels)]: Set(0) {}
        }
      }
    },
    stale: false,
    compatible: true,
  code: undefined,
  [Symbol(errorLabels)]: Set(0) {}
}

【问题讨论】:

标签: node.js mongodb


【解决方案1】:

尝试将 mongodb://localhost:27017 更改为 mongodb://127.0.0.1:27017 有时无法识别本地主机。

希望对您有所帮助

【讨论】:

    猜你喜欢
    • 2016-12-01
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2019-12-23
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多