我正在尝试使用Node.js连接到MongoDb,但在查看了许多教程后遇到了这个错误。

16 浏览
0 Comments

我正在尝试使用Node.js连接到MongoDb,但在查看了许多教程后遇到了这个错误。

const timeoutError = new error_1.MongoServerSelectionError(`在 ${serverSelectionTimeoutMS} 毫秒后,服务器选择超时`, this.description);

MongoServerSelectionError: 连接 ECONNREFUSED ::1:27017

at Timeout._onTimeout (D:\Coding\web\node_modules\mongodb\lib\sdam\topology.js:293: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 {

_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },

address: 'localhost:27017',

type: 'Unknown',

hosts: [],

passives: [],

arbiters: [],

tags: {},

minWireVersion: 0,

maxWireVersion: 0,

roundTripTime: -1,

lastUpdateTime: 72838933,

lastWriteDate: 0,

error: MongoNetworkError: 连接 ECONNREFUSED ::1:27017

at connectionFailureError (D:\Coding\web\node_modules\mongodb\lib\cmap\connect.js:379:20)

at Socket. (D:\Coding\web\node_modules\mongodb\lib\cmap\connect.js:302: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) {

[Symbol(errorLabels)]: Set(0) {}

}

}

},

stale: false,

compatible: true,

heartbeatFrequencyMS: 10000,

localThresholdMS: 15,

logicalSessionTimeoutMinutes: undefined

},

code: undefined,

[Symbol(errorLabels)]: Set(0) {}

}

Node.js v18.7.0

[nodemon] 应用程序崩溃 - 等待文件更改后重新启动...

代码如下:

const mongoose = require("mongoose");

const MongoUrl = "mongodb://localhost:27017";

const mongoConnect = () => {

mongoose.connect(MongoUrl, (err)=>{

if(!err)

{

console.log("已连接");

}

else{

console.log("未连接");

}

})

};

mongoConnect();

0
0 Comments

在使用Node.js连接MongoDb时,面对这个错误可能的原因是mongod可能没有激活。

如果你使用基于Linux的操作系统,请尝试以下命令来检查mongodb的状态:

sudo systemctl status mongod

如果状态是运行中:

● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: active (running) since Wed 2020-10-14 14:13:40 UTC; 3s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 1604 (mongod)
     Memory: 210.8M
     CGroup: /system.slice/mongod.service
             └─1604 /usr/bin/mongod --config /etc/mongod.conf

如果状态是停止的:

● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: inactive (dead)
       Docs: https://docs.mongodb.org/manual

要启动mongodb,请执行以下命令:

sudo systemctl start mongod

参考来源:Is mongodb running?

如果你使用的是Windows系统,只需执行以下命令即可启动MongoDB:

mongo

0