MongooseServerSelectionError: 连接错误,ECONNREFUSED ::1:27017。

huangapple go评论81阅读模式
英文:

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. (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
}

我原本期望在控制台看到连接成功的消息,请帮帮我"


<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: &#39;Unknown&#39;,
    servers: Map(1) {
      &#39;localhost:27017&#39; =&gt; ServerDescription {
        address: &#39;localhost:27017&#39;,
        type: &#39;Unknown&#39;,
        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.&lt;anonymous&gt; (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: &#39;ECONNREFUSED&#39;,
            syscall: &#39;connect&#39;,
            address: &#39;::1&#39;,
            port: 27017
          },
          [Symbol(errorLabels)]: Set(1) { &#39;ResetPool&#39; }
        },
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        &#39;$clusterTime&#39;: 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("连接成功");
})
  1. 要么 使用 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),

  1. Either replace localhost with 127.0.0.1.
mongoose.connect(&quot;mongodb://127.0.0.1:27017/schooldb&quot;).then(() =&gt; {
    console.log(&quot;connection successfully &quot;);
})
  1. OR use family: 4 parameter. This tells the node.js localhost to use ipv4 address.
mongoose.connect(&quot;mongodb://localhost:27017/schooldb&quot;,{
    family: 4,
}).then(() =&gt; {
    console.log(&quot;connection successfully &quot;);
})

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(&quot;mongodb://0.0.0.0:27017/schooldb&quot;).then(() =&gt; {
    console.log(&quot;connection successfully &quot;);
})

答案3

得分: 0

在我的情况下,我只是将连接字符串从 'mongodb://localhost/MyDBName' 替换为 'mongodb://127.0.0.1:27017/MyDBName'。另外,请确保MongoDB服务器正在运行。

MongooseServerSelectionError: 连接错误,ECONNREFUSED ::1:27017。

英文:

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.

MongooseServerSelectionError: 连接错误,ECONNREFUSED ::1:27017。

答案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

huangapple
  • 本文由 发表于 2023年5月22日 16:06:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76304154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定