Mongoose "MongooseServerSelectionError" in CI
Mongoose wraps the driver server-selection failure in a MongooseServerSelectionError. It could not find a reachable server before serverSelectionTimeoutMS elapsed. The wrapped reason (ECONNREFUSED, ENOTFOUND, auth) tells you why.
What this error means
Mongoose rejects connect() with "MongooseServerSelectionError:" followed by the underlying reason, after a pause equal to the selection timeout.
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.openUri (/app/node_modules/mongoose/lib/connection.js:825:32)Common causes
The wrapped reason is the real cause
ECONNREFUSED means mongod is not up; ENOTFOUND means DNS/host is wrong; an auth reason means credentials failed. Read the text after the colon.
A short selection timeout hides a slow startup
On a busy runner the server is not ready before the default timeout, so Mongoose gives up early.
How to fix it
Fix the wrapped reason, then connect after readiness
- Read the underlying reason in the message and address it (start mongod, fix host, fix creds).
- Connect only after the service healthcheck passes.
- Keep a sane
serverSelectionTimeoutMSso failures surface quickly but not prematurely.
await mongoose.connect(process.env.MONGODB_URI, {
serverSelectionTimeoutMS: 10000,
});Ensure the service is healthy first
Gate the job on a mongo healthcheck so Mongoose connects only once mongod accepts connections.
options: >-
--health-cmd "mongosh --eval 'db.adminCommand({ping:1})'"
--health-interval 5s --health-retries 10How to prevent it
- Always read the wrapped reason before changing timeouts.
- Connect after a healthcheck confirms mongod is ready.
- Keep credentials and host in synced secrets.