You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express连接MongoDB遇MongooseServerSelectionError:ECONNREFUSED错误求助

解决Express连接MongoDB的ECONNREFUSED错误

问题代码

用户尝试通过Express连接本地MongoDB的server.js代码如下:

import express from 'express';
import bodyParser from 'body-parser';
import userRoutes from './routes/users.js';
import mongoose from 'mongoose';

const app = express();
const PORT = 4000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use('/users', userRoutes);

mongoose.Promise = global.Promise;

mongoose.connect("mongodb://localhost:27017/articlesdb", {
    useNewUrlParser: true
  })
  .then(() => {
    console.log("database connected");
  })
  .catch(err => {
    console.log("Could not connect", err);
  });
  
app.get('/', (req, res) => {
    console.log('[TEST]!');
    res.send('Hello from homepage.');
});

app.listen(PORT, () =`enter code here`> console.log(`Server is Running on port: http://localhost:${PORT}`));

错误信息

运行代码后收到的错误:

Could not connect MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at Connection.openUri (D:\Vue Practice Project\instant-search-project\node_modules\mongoose\lib\connection.js:824:32)
at D:\Vue Practice Project\instant-search-project\node_modules\mongoose\lib\index.js:381:10
at D:\Vue Practice Project\instant-search-project\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise ()
at promiseOrCallback (D:\Vue Practice Project\instant-search-project\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (D:\Vue Practice Project\instant-search-project\node_modules\mongoose\lib\index.js:1234:10)
at Mongoose.connect (D:\Vue Practice Project\instant-search-project\node_modules\mongoose\lib\index.js:380:20)
at file:///D:/Vue%20Practice%20Project/instant-search-project/server.js:27:10
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}

排查与解决步骤

1. 确认MongoDB服务已启动

ECONNREFUSED表示目标端口无服务响应,先检查MongoDB服务状态:

  • Windows:打开「服务」面板,找到MongoDB服务,确保状态为「正在运行」;或执行命令 net start MongoDB 启动服务
  • macOS/Linux:若用brew安装,执行 brew services start mongodb-community;若用系统服务,执行 sudo systemctl start mongod

2. 强制使用IPv4连接地址

部分环境中localhost会解析到IPv6地址::1,但MongoDB默认可能仅监听IPv4的127.0.0.1。修改连接字符串:

mongoose.connect("mongodb://127.0.0.1:27017/articlesdb", {
    useNewUrlParser: true
})

3. 修正代码语法错误

原代码中app.listen的回调函数存在输入错误,修正为:

app.listen(PORT, () => console.log(`Server is Running on port: http://localhost:${PORT}`));

4. 检查MongoDB绑定IP配置

打开MongoDB配置文件(如mongod.conf),确认bindIp设置为127.0.0.1(仅允许本地)或0.0.0.0(允许所有IP),避免因绑定特定IP导致无法连接。

修正后完整代码

import express from 'express';
import bodyParser from 'body-parser';
import userRoutes from './routes/users.js';
import mongoose from 'mongoose';

const app = express();
const PORT = 4000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use('/users', userRoutes);

mongoose.Promise = global.Promise;

mongoose.connect("mongodb://127.0.0.1:27017/articlesdb", {
    useNewUrlParser: true
  })
  .then(() => {
    console.log("database connected");
  })
  .catch(err => {
    console.log("Could not connect", err);
  });
  
app.get('/', (req, res) => {
    console.log('[TEST]!');
    res.send('Hello from homepage.');
});

app.listen(PORT, () => console.log(`Server is Running on port: http://localhost:${PORT}`));

内容的提问来源于stack exchange,提问作者GulamMd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:05:28