You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Node.js连接MongoDB时出现connect ECONNREFUSED错误的求助

Fixing "connect ECONNREFUSED 127.0.0.1:27017" in Mongoose/Node.js

Hey there! Don't stress—this is one of the most common issues when you're just getting started with MongoDB and Mongoose, and it's usually easy to fix. Let's go through the most likely solutions step by step, since you're new to all this I'll keep things super clear.

1. Make sure MongoDB is actually running on your computer

The "ECONNREFUSED" error basically means your Node.js app is trying to talk to MongoDB at localhost:27017, but there's no program listening there. Here's how to check and start it:

On Windows:

  • Press Win + R, type services.msc, and hit Enter.
  • Look for a service named MongoDB (it might be called MongoDB Server or something similar).
  • If it's not running, right-click it and select "Start". You can also set it to "Automatic" so it starts when your computer boots up.

Alternatively, start it via command prompt (run as Administrator):

net start MongoDB

On Mac:

If you installed MongoDB using Homebrew, open Terminal and run:

brew services start mongodb-community

On Linux (like Ubuntu):

Open Terminal and run:

sudo systemctl start mongod

2. Update your code with better connection handling

Your current code is almost right, but adding a few options and error feedback will help you confirm if things work. Update your code to this:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mongotest', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => console.log('Successfully connected to MongoDB! 🎉'))
.catch(err => console.error('Failed to connect:', err));

This does two key things:

  • The options (useNewUrlParser, useUnifiedTopology) fix deprecated warnings in older Mongoose versions.
  • The .then() and .catch() blocks give you clear feedback instead of just throwing an uncaught error.

3. If MongoDB isn't set up as a service, start it manually

If you can't find the MongoDB service at all, it might mean you didn't set it up during installation. No problem—you can start it manually:

  1. Locate your MongoDB installation folder (usually C:\Program Files\MongoDB\Server\X.X\bin on Windows, or /usr/local/bin on Mac/Linux).
  2. Open a terminal/command prompt in that folder.
  3. Run mongod.exe (Windows) or mongod (Mac/Linux). This starts the MongoDB server manually—keep this terminal window open while you run your app!
  4. Now run your Node.js app again.

Once you see the "Successfully connected" message, you're good to go! If you still hit issues, double-check each step—nine times out of ten it's just the MongoDB server not being started.

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

火山引擎 最新活动