payloadcms/payload · critical · Error

Error: cannot connect to MongoDB: ${msg}

Error message

Error: cannot connect to MongoDB: ${msg}

What it means

connect()'s try block wraps mongoose.createConnection, openUri, dropDatabase, ensureIndexes, and prod migrations. Any thrown error is enriched with its message and re-thrown. This is a catch-and-rethrow wrapper; the real cause is in err.message and the payload.logger.error output.

Source

Thrown at packages/db-mongodb/src/connect.ts:115

        }),
      )
    }

    if (process.env.NODE_ENV === 'production' && this.prodMigrations) {
      await this.migrate({ migrations: this.prodMigrations as unknown as Migration[] })
    }
  } catch (err) {
    let msg = `Error: cannot connect to MongoDB.`

    if (typeof err === 'object' && err && 'message' in err && typeof err.message === 'string') {
      msg = `${msg} Details: ${err.message}`
    }

    this.payload.logger.error({
      err,
      msg,
    })
    throw new Error(`Error: cannot connect to MongoDB: ${msg}`)
  }
}

View on GitHub (pinned to 00c58b35c0)

Solutions

  1. Read the 'Details: ...' portion of the message — it carries the mongoose/mongo driver error (auth, timeout, etc.).
  2. Verify the connection string, credentials, and that the host/port are reachable (e.g. mongosh, telnet).
  3. For Atlas, add the client IP to the cluster's network allowlist and confirm the user has the right role.
  4. If using a replica set, ensure all members are reachable and a primary can be elected.

Example fix

// before
new MongooseAdapter({
  payload,
  url: 'mongodb+srv://user:wrongpass@cluster.mongodb.net/db',
})

// after
new MongooseAdapter({
  payload,
  url: process.env.DATABASE_URI, // verified correct creds + allowlisted IP
})
Defensive patterns

Strategy: try-catch

Validate before calling

import { MongoClient } from 'mongodb'

async function assertMongoReachable(uri: string) {
  const client = new MongoClient(uri, { serverSelectionTimeoutMS: 5000 })
  try {
    await client.db().command({ ping: 1 })
  } finally {
    await client.close()
  }
}

Try / catch

try {
  await payload.db.connect()
} catch (e) {
  if (e instanceof Error && e.message.includes('cannot connect to MongoDB')) {
    payload.logger.error('Mongo unreachable — verify URI, credentials, IP allowlist, and TLS')
  }
  throw e
}

Prevention

When it happens

Trigger: Wrong/missing credentials (auth failed), unreachable host, DNS failure, firewall blocking the mongo port, replica set unable to elect a primary, IP allowlist blocking the client, expired TLS cert, or dropDatabase/ensureIndexes failing mid-connect.

Common situations: Atlas cluster with client IP not allowlisted; wrong username/password in the URI; SRV record mismatch; connecting to a replica set as standalone; cert/TLS issues; local mongod not running.

Related errors


AI-assisted analysis of payloadcms/payload@00c58b35c0 (2026-08-12). Data as JSON: /api/errors/71ac0d28f06d93a7. Report an issue: GitHub.