[英]MongoDB database operations not working in NodeJS
我正在嘗試在 Node.js 中使用 MongoDB,但它無法使用最簡單的代碼。
最簡單的代碼:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function (err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
錯誤:
D:\Clg\Sem-5\Software Packages\Lab\Practical-7\node_modules\mongodb\lib\sdam\topology.js:292
const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
^
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (D:\Clg\Sem-5\Software Packages\Lab\Practical-7\node_modules\mongodb\lib\sdam\topology.js:292: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 {
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 2642697,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (D:\Clg\Sem-5\Software Packages\Lab\Practical-7\node_modules\mongodb\lib\cmap\connect.js:387:20)
at Socket.<anonymous> (D:\Clg\Sem-5\Software Packages\Lab\Practical-7\node_modules\mongodb\lib\cmap\connect.js:310: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) {
cause: Error: connect ECONNREFUSED ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 27017
},
[Symbol(errorLabels)]: Set(1) { 'ResetPool' }
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
'$clusterTime': null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.7.0
我在最新版本和 v5.0.13 中都測試了錯誤,但我有同樣的錯誤,當我在互聯網上搜索時,我發現 MongoDB 服務應該有問題,但是當我檢查相同的時候。 我發現服務已經在運行。
ECONNREFUSED
通常表示 MongoDB 未在您提供的 URL 上運行,或者您的應用程序無法訪問該端口。 您確定在本地端口號 27017 上運行 MongoDB 嗎? 您將需要確保您的本地 MongoDB 實例已啟動且可用 - 嘗試通過瀏覽器導航到localhost:27017
來訪問它。
更改給定路徑中的文件將很有幫助
"C:\Program Files\MongoDB\Server\5.0\bin\mongod.cfg"
至少這 4 行必須在“凈”部分內
net:
port: 27017
bindIp: 127.0.0.1
ipv6: true
bindIpAll: true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.