执行node index.js时遇MongoNetworkError连接MongoDB失败求助
Hey there, let’s troubleshoot that MongoDB connection failure you’re hitting. The ECONNREFUSED error almost always means your Node.js app can’t reach a running MongoDB instance on port 27017. Here are the step-by-step fixes to get this sorted:
1. Check if MongoDB is running locally
This is the most common culprit. Depending on your operating system, use these commands to verify and start the service:
- Mac (Homebrew):
- Check service status:
brew services list - Start MongoDB:
brew services start mongodb-community
- Check service status:
- Windows:
- Open the Services app (press Win + R, type
services.msc), locate "MongoDB Server", and ensure it’s marked as "Running". If not, right-click and select "Start".
- Open the Services app (press Win + R, type
- Linux (Ubuntu/Debian):
- Check service status:
sudo systemctl status mongod - Start MongoDB:
sudo systemctl start mongod
- Check service status:
2. Verify the port matches your MongoDB configuration
By default, MongoDB uses port 27017, but if you’ve modified your mongod.conf file to use a different port, you need to update your connection string in index.js to match. For example:
// If MongoDB is configured for port 27018, update your connection string: mongoose.connect('mongodb://localhost:27018/your-database-name');
3. Test the connection directly with MongoDB Shell
Run the mongosh command in your terminal. If this fails to connect, the issue is definitely with the MongoDB service (not your Node.js code). If it connects successfully, double-check your connection string in index.js for typos—like misspelling localhost or using the wrong database name.
4. Check for firewall/security software interference
Sometimes local firewalls or antivirus tools block incoming connections to port 27017. Temporarily disable your firewall/security software and try running node index.js again. If it works, add an exception for MongoDB in your security settings to keep the connection working long-term.
5. Fix the UnhandledPromiseRejectionWarning
While this isn’t the root cause of the connection failure, it’s important to handle promise rejections properly to avoid warnings. Update your connection code to include error handling:
// Using .then/.catch syntax mongoose.connect('mongodb://localhost:27017/your-database-name') .then(() => console.log('Successfully connected to MongoDB')) .catch(err => console.error('MongoDB connection failed:', err)); // Or using async/await with try/catch async function connectToDB() { try { await mongoose.connect('mongodb://localhost:27017/your-database-name'); console.log('Successfully connected to MongoDB'); } catch (err) { console.error('MongoDB connection failed:', err); } } connectToDB();
Start with step 1—nine times out of ten, the issue is just that MongoDB isn’t running. Let me know if any of these steps get you up and running!
内容的提问来源于stack exchange,提问作者ApplePie

