{"record":{"id":"71ac0d28f06d93a7","repo":"payloadcms/payload","slug":"error-cannot-connect-to-mongodb-msg","errorCode":null,"errorMessage":"Error: cannot connect to MongoDB: ${msg}","messagePattern":"Error: cannot connect to MongoDB: (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"critical","filePath":"packages/db-mongodb/src/connect.ts","lineNumber":115,"sourceCode":"        }),\n      )\n    }\n\n    if (process.env.NODE_ENV === 'production' && this.prodMigrations) {\n      await this.migrate({ migrations: this.prodMigrations as unknown as Migration[] })\n    }\n  } catch (err) {\n    let msg = `Error: cannot connect to MongoDB.`\n\n    if (typeof err === 'object' && err && 'message' in err && typeof err.message === 'string') {\n      msg = `${msg} Details: ${err.message}`\n    }\n\n    this.payload.logger.error({\n      err,\n      msg,\n    })\n    throw new Error(`Error: cannot connect to MongoDB: ${msg}`)\n  }\n}\n","sourceCodeStart":97,"sourceCodeEnd":118,"githubUrl":"https://github.com/payloadcms/payload/blob/00c58b35c0ed348ddc22daabf467b139727214fd/packages/db-mongodb/src/connect.ts#L97-L118","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Read the 'Details: ...' portion of the message — it carries the mongoose/mongo driver error (auth, timeout, etc.).","Verify the connection string, credentials, and that the host/port are reachable (e.g. mongosh, telnet).","For Atlas, add the client IP to the cluster's network allowlist and confirm the user has the right role.","If using a replica set, ensure all members are reachable and a primary can be elected."],"exampleFix":"// before\nnew MongooseAdapter({\n  payload,\n  url: 'mongodb+srv://user:wrongpass@cluster.mongodb.net/db',\n})\n\n// after\nnew MongooseAdapter({\n  payload,\n  url: process.env.DATABASE_URI, // verified correct creds + allowlisted IP\n})","handlingStrategy":"try-catch","validationCode":"import { MongoClient } from 'mongodb'\n\nasync function assertMongoReachable(uri: string) {\n  const client = new MongoClient(uri, { serverSelectionTimeoutMS: 5000 })\n  try {\n    await client.db().command({ ping: 1 })\n  } finally {\n    await client.close()\n  }\n}","typeGuard":null,"tryCatchPattern":"try {\n  await payload.db.connect()\n} catch (e) {\n  if (e instanceof Error && e.message.includes('cannot connect to MongoDB')) {\n    payload.logger.error('Mongo unreachable — verify URI, credentials, IP allowlist, and TLS')\n  }\n  throw e\n}","preventionTips":["Test the URI with mongosh before starting Payload.","For Atlas, allowlist the client IP and verify user roles.","Ensure replica set members are reachable if connecting to an RS."],"tags":["db-mongodb","database","connection","network","adapter"],"backgroundTag":null,"analyzedSha":"00c58b35c0ed348ddc22daabf467b139727214fd","analyzedAt":"2026-08-12T20:45:03.758Z","schemaVersion":2},"datasetVersion":"2026-08-12T23:17:12.415Z"}