MongooseServerSelectionError连接被拒绝问题求助:mongod服务运行但Node.js服务器启动后崩溃
Hey there! Let’s troubleshoot this MongoDB connection issue you’re hitting. That error message makes it clear your Node.js app can’t establish a connection to your local MongoDB server on port 27017. Here are the step-by-step fixes to get you back on track with your MERN course:
1. Make sure MongoDB is actually running
First things first—if the MongoDB service isn’t active, nothing will be able to connect to it:
- On Windows: Open the Services app (press Win+R, type
services.msc), find the MongoDB service, and check if its status is "Running". If not, right-click it and select "Start". You can also runnet start MongoDBin an elevated Command Prompt. - On Mac: If you installed via Homebrew, run
brew services start mongodb-community. - On Linux: Run
sudo systemctl start mongod.
2. Switch your connection string to use IPv4
Node.js 17+ (which you’re running, v17.4.0) prioritizes IPv6 addresses by default, but many local MongoDB installations aren’t configured to listen on IPv6. Update your connection string in index.js:
Instead of:
mongoose.connect('mongodb://localhost:27017/yourDatabaseName')
Use:
mongoose.connect('mongodb://127.0.0.1:27017/yourDatabaseName')
This forces the connection to use IPv4, which is almost always enabled for local MongoDB setups.
3. Verify connectivity with MongoDB Compass
You mentioned having a Compass screenshot—test the connection there first to rule out server-side issues:
- Try connecting to
mongodb://127.0.0.1:27017in Compass. If it works, the problem is definitely in your code’s connection string. - If Compass also can’t connect, go back to step 1 and double-check the MongoDB service, or move to the next step.
4. Check MongoDB’s bind IP configuration (advanced)
If the above steps don’t work, your MongoDB might be restricted to specific IP addresses:
- Locate your
mongod.conffile (on Windows, this is usually inC:\Program Files\MongoDB\Server\<your-version>\bin\mongod.cfg). - Look for the
net.bindIpsetting. Ensure it’s set to127.0.0.1(allows local connections) or0.0.0.0(allows all connections). - Save the file and restart the MongoDB service.
Bonus: Check version compatibility
Make sure your Mongoose version plays nice with your MongoDB version. For example, Mongoose 6.x requires MongoDB 4.0 or newer. You can check your Mongoose version with npm list mongoose in your backend folder.
If you still run into issues after trying these steps, share your index.js code and the MongoDB Compass screenshot—those will help narrow things down further!
内容的提问来源于stack exchange,提问作者Paradox_0

