Skip to content
Latchkey

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.

node
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

  1. Read the underlying reason in the message and address it (start mongod, fix host, fix creds).
  2. Connect only after the service healthcheck passes.
  3. Keep a sane serverSelectionTimeoutMS so failures surface quickly but not prematurely.
db.js
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.

.github/workflows/ci.yml
options: >-
  --health-cmd "mongosh --eval 'db.adminCommand({ping:1})'"
  --health-interval 5s --health-retries 10

How 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.

Frequently asked questions

What causes ""MongooseServerSelectionError""?
ECONNREFUSED means mongod is not up; ENOTFOUND means DNS/host is wrong; an auth reason means credentials failed. Read the text after the colon.
How do I fix "MongooseServerSelectionError"?
Fix the wrapped reason, then connect after readiness

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card