英文:
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 error
问题
// 以下是要翻译的内容:
import express from 'express'
const app = express();
const port = process.env.PORT || 8000;
import mongoose from 'mongoose';
mongoose.connect("mongodb://localhost:27017/schooldb").then(() => {
console.log("连接成功");
})
app.get('/', (req, res) => {
res.send('你好,用户')
})
app.listen(port, () => {
console.log(`监听端口 http://localhost:${port}`);
})
"嗨,我是新手学习Express,我正在尝试将我的MongoDB连接到Express.js,我无法理解这个错误
D:\Learn\Learn Express\ new_mongoose\node_modules\mongoose\lib\connection.js:792
err = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at _handleConnectionErrors (D:\Learn\Learn Express\new_mongoose\node_modules\mongoose\lib\connection.js:792:11)
at NativeConnection.openUri (D:\Learn\Learn Express\new_mongoose\node_modules\mongoose\lib\connection.js:767:11)
at runNextTicks (node:internal/process/task_queues:60:5)
at listOnTimeout (node:internal/timers:533:9)
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: 656213806,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (D:\Learn\Learn Express\new_mongoose\node_modules\mongodb\lib\cmap\connect.js:370:20)
at Socket.
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:1487: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
}
我原本期望在控制台看到连接成功的消息,请帮帮我"
<details>
<summary>英文:</summary>
import express from 'express'
const app = express();
const port = process.env.PORT || 8000;
import mongoose from 'mongoose';
mongoose.connect("mongodb://localhost:27017/schooldb").then(() => {
console.log("connection successfully ");
})
app.get('/', (req, res) => {
res.send('Hello user')
})
app.listen(port, () => {
console.log(listening at port http://localhost:${port}
);
})
Hii i am new to learn express , i am trying to connect my mongodb to express js, i am not able to understand this error
D:\Learn\Learn Express\ new_mongoose\node_modules\mongoose\lib\connection.js:792
err = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at _handleConnectionErrors (D:\Learn\Learn Express\new_mongoose\node_modules\mongoose\lib\connection.js:792:11)
at NativeConnection.openUri (D:\Learn\Learn Express\new_mongoose\node_modules\mongoose\lib\connection.js:767:11)
at runNextTicks (node:internal/process/task_queues:60:5)
at listOnTimeout (node:internal/timers:533:9)
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: 656213806,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (D:\Learn\Learn Express\new_mongoose\node_modules\mongodb\lib\cmap\connect.js:370:20)
at Socket.<anonymous> (D:\Learn\Learn Express\new_mongoose\node_modules\mongodb\lib\cmap\connect.js:293: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:1487: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
}
i was expecting connection successfull message at console,please help me
</details>
# 答案1
**得分**: 2
在node.js v18中,localhost使用ipv6地址(`::1`),并且默认情况下mongodb的localhost没有启用ipv6。这就是为什么您面临此问题的原因。
如果您想使用ipv4 localhost地址(`127.0.0.1`):
1. **要么** 将 `localhost` 替换为 `127.0.0.1`。
```js
mongoose.connect("mongodb://127.0.0.1:27017/schooldb").then(() => {
console.log("连接成功");
})
- 要么 使用
family: 4
参数。这告诉node.js localhost使用ipv4地址。
mongoose.connect("mongodb://localhost:27017/schooldb", {
family: 4,
}).then(() => {
console.log("连接成功");
})
要么
如果您想使用ipv6地址,只需使用mongod
带 --ipv6
参数启动。这会启用mongodb的ipv6地址。
mongod --ipv6
英文:
In node.js v18, localhost uses ipv6 address (::1
), and by default mongodb localhost doesn't have ipv6 enabled. That's why you're facing this issue.
If you want to use ipv4 localhost address (127.0.0.1
),
- Either replace
localhost
with127.0.0.1
.
mongoose.connect("mongodb://127.0.0.1:27017/schooldb").then(() => {
console.log("connection successfully ");
})
- OR use
family: 4
parameter. This tells the node.js localhost to use ipv4 address.
mongoose.connect("mongodb://localhost:27017/schooldb",{
family: 4,
}).then(() => {
console.log("connection successfully ");
})
OR
If you want to use the ipv6 address, then just start mongod
with --ipv6
as argument. This enables mongodb ipv6 address.
mongod --ipv6
答案2
得分: 0
这里 MongoDB 试图连接到当前系统,但由于数据库未在当前系统上运行而无法连接。要解决此问题,请使用 0.0.0.0
替代 localhost。
mongoose.connect("mongodb://0.0.0.0:27017/schooldb").then(() => {
console.log("连接成功");
})
英文:
here mongodb trying to connect to the current system but it fails to connect because the database is not running on the current system to fix this use 0.0.0.0
instead of localhost.
mongoose.connect("mongodb://0.0.0.0:27017/schooldb").then(() => {
console.log("connection successfully ");
})
答案3
得分: 0
在我的情况下,我只是将连接字符串从 'mongodb://localhost/MyDBName' 替换为 'mongodb://127.0.0.1:27017/MyDBName'。另外,请确保MongoDB服务器正在运行。
英文:
In my case, I simply replaced the connection string from 'mongodb://localhost/MyDBName' with 'mongodb://127.0.0.1:27017/MyDBName'.
Also, please ensure that the MongoDB server is up and running.
答案4
得分: 0
以下是已翻译的内容:
在我的情况下,问题出在mongodb访问权限上,以下是我解决问题的方法
正确的文件权限
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chmod -R 0755 /var/lib/mongodb
sudo chown -R mongodb:mongodb /var/log/mongodb
sudo chmod -R 0755 /var/log/mongodb
移除不正确的所有权
sudo chown mongodb:mongodb /var/lib/mongodb/WiredTiger.turtle
sudo chown mongodb:mongodb /var/lib/mongodb/collection-0--9070219476800958121.wt
启动mongod
sudo systemctl start mongod
检查MongoDB状态
sudo systemctl status mongod
英文:
In my case the issue was on mongodb access permission and here's how I solve it
Correct File Permissions
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chmod -R 0755 /var/lib/mongodb
sudo chown -R mongodb:mongodb /var/log/mongodb
sudo chmod -R 0755 /var/log/mongodb
Remove Incorrect Ownership
sudo chown mongodb:mongodb /var/lib/mongodb/WiredTiger.turtle
sudo chown mongodb:mongodb /var/lib/mongodb/collection-0--9070219476800958121.wt
Start mongod
sudo systemctl start mongod
Check MongoDB Status
sudo systemctl status mongod
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论