Node.js连接MongoDB时出现connect ECONNREFUSED错误的求助
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, typeservices.msc, and hit Enter. - Look for a service named MongoDB (it might be called
MongoDB Serveror 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:
- Locate your MongoDB installation folder (usually
C:\Program Files\MongoDB\Server\X.X\binon Windows, or/usr/local/binon Mac/Linux). - Open a terminal/command prompt in that folder.
- Run
mongod.exe(Windows) ormongod(Mac/Linux). This starts the MongoDB server manually—keep this terminal window open while you run your app! - 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




