我想将我的节点 js 连接到 mongodb。 --> 我正在使用 mongodb 版本 6.5.0(将其作为服务安装 [完整安装]) --> 我还安装了 mongosh(mongodb 终端) --> 我可以使用 mongosh 终端访问和修改我的数据库(所有命令都在终端中运行) --> 在我的项目文件夹中,我首先执行了“npm init”,然后是“npm install node”,然后是“npm install mongodb”(驱动程序),我使用的是 nodeJS 版本 18.15.0 我在“connect.js”文件中的代码如下:
const {MongoClient} = require('mongodb');
const MONGO_URL = 'mongodb://localhost:27017';
const DB_NAME = 'tododb';
// ASYNC IIFE
(async () =>{
const client = await MongoClient.connect(MONGO_URL)
const tododb = client.db(DB_NAME)
console.log(tododb)
})()
当我在 vs 代码终端中执行“node connect.js”时出现此错误
C:\Users\Gaurav\Desktop\Gagan\DEV\mongoBasics\node_modules\mongodb\lib\sdam\topology.js:277
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\Gaurav\Desktop\Gagan\DEV\mongoBasics\node_modules\mongodb\lib\sdam\topology.js:277:38)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512: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: 1431144101,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\Gaurav\Desktop\Gagan\DEV\mongoBasics\node_modules\mongodb\lib\cmap\connect.js:383:20)
at Socket.<anonymous> (C:\Users\Gaurav\Desktop\Gagan\DEV\mongoBasics\node_modules\mongodb\lib\cmap\connect.js:307: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:1494: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.15.0
我想将我的 nodeJS 与 mongoDB 一起使用
您正在尝试通过 ipV6 连接,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
行表明;按照@Muhammad Fazeel 的建议,将 MONGO_URL
更改为 mongodb://127.0.0.1:27017