我正在尝试从头开始学习 Node.JS。当我尝试将
index.js
连接到 MongoDB 指南针时,出现错误:
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at _handleConnectionErrors (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongoose/lib/connection.js:897:11)
at NativeConnection.openUri (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongoose/lib/connection.js:848:11) {
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,
minRoundTripTime: 0,
lastUpdateTime: 31356356,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
at connectionFailureError (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongodb/lib/cmap/connect.js:353:20)
at Socket.<anonymous> (/mnt/c/Users/user/Desktop/Programming/website/learningNode/mongoose/node_modules/mongodb/lib/cmap/connect.js:268:44)
at Object.onceWrapper (node:events:635:26)
at Socket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:170:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
[Symbol(errorLabels)]: Set(1) { 'ResetPool' },
[cause]: Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1607:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 27017
}
},
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
}
我已经使用 mongosh 来确保连接字符串正确并且工作正常。 MongoDB 服务已启动并运行。
import express from "express";
import mongoose from "mongoose";
import dotenv from "dotenv";
// Create an Express app
const app = express();
// Load environment variables from .env file
dotenv.config();
// Set the port from environment variables or default to 7000
const PORT = process.env.PORT || 7000;
// Get the MongoDB connection URL from environment variables
const MONGOURL = process.env.MONGO_URL;
// Connect to MongoDB and start the server
mongoose.connect(MONGOURL).then(() => {
console.log("Database connected successfully.");
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
});
PORT = 8000
MONGO_URL = "mongodb://localhost:27017/dbconnect"
设置非常基本,我不知道如何解决它。
我尝试过使用 localhost、127.0.0.1 或 0.0.0.0 来使用各种连接字符串。