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

MongooseServerSelectionError连接被拒绝问题求助:mongod服务运行但Node.js服务器启动后崩溃

Fixing MongooseServerSelectionError: connect ECONNREFUSED ::1:27017

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 run net start MongoDB in 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:27017 in 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.conf file (on Windows, this is usually in C:\Program Files\MongoDB\Server\<your-version>\bin\mongod.cfg).
  • Look for the net.bindIp setting. Ensure it’s set to 127.0.0.1 (allows local connections) or 0.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:47:39