{"record":{"id":"9a2ca1237cf612dc","repo":"payloadcms/payload","slug":"begintransaction-called-while-no-connection-to-the","errorCode":null,"errorMessage":"beginTransaction called while no connection to the database exists","messagePattern":"beginTransaction called while no connection to the database exists","errorType":"http","errorClass":"APIError","httpStatus":500,"severity":"critical","filePath":"packages/db-mongodb/src/transactions/beginTransaction.ts","lineNumber":17,"sourceCode":"import type { TransactionOptions } from 'mongodb'\nimport type { BeginTransaction } from 'payload'\n\nimport { APIError } from 'payload'\nimport { v4 as uuid } from 'uuid'\n\nimport type { MongooseAdapter } from '../index.js'\n\n// Needs await to fulfill the interface\n// @ts-expect-error TransactionOptions isn't compatible with BeginTransaction of the DatabaseAdapter interface.\n// eslint-disable-next-line @typescript-eslint/require-await\nexport const beginTransaction: BeginTransaction = async function beginTransaction(\n  this: MongooseAdapter,\n  options: TransactionOptions,\n) {\n  if (!this.connection) {\n    throw new APIError('beginTransaction called while no connection to the database exists')\n  }\n\n  const client = this.connection.getClient()\n  const id = uuid()\n\n  if (!this.sessions[id]) {\n    this.sessions[id] = client.startSession()\n  }\n  if (this.sessions[id]?.inTransaction()) {\n    this.payload.logger.warn('beginTransaction called while transaction already exists')\n  } else {\n    this.sessions[id]?.startTransaction(options || (this.transactionOptions as TransactionOptions))\n  }\n\n  return id\n}\n","sourceCodeStart":1,"sourceCodeEnd":34,"githubUrl":"https://github.com/payloadcms/payload/blob/00c58b35c0ed348ddc22daabf467b139727214fd/packages/db-mongodb/src/transactions/beginTransaction.ts#L1-L34","documentation":"Thrown by the MongoDB adapter's `beginTransaction` when `this.connection` is falsy — Mongoose has no live connection. Transactions require a session bound to an active connection, so the adapter aborts immediately instead of producing a useless session.","triggerScenarios":"Any transactional operation (payload.db.beginTransaction, or any op wrapped in a transaction) that runs before `payload.init()`/`connect` resolves, after the connection was closed/dropped, or when the initial connect failed but the app kept serving requests.","commonSituations":"Handling requests during startup before the init promise resolves; MongoDB unreachable at boot but the process continues; calling `mongoose.disconnect()`/`db.close()` then querying; serverless cold-start races where the connection isn't established before the first transactional request.","solutions":["Await `payload.init()` (and the underlying connect) before serving any request.","Verify the MongoDB URI/host is reachable and credentials are valid.","Guard with `adapter.connection && adapter.connection.readyState === 1` before starting a transaction.","In serverless, reuse the connection across invocations and do not close it between calls."],"exampleFix":"// before\napp.post('/x', handler) // starts before DB is up\n// after\nawait payload.init()\napp.post('/x', handler)","handlingStrategy":"validation","validationCode":"function assertConnected(adapter) {\n  if (!adapter.connection || adapter.connection.readyState !== 1)\n    throw new Error('MongoDB connection not ready')\n}","typeGuard":"const isMongoConnected = (adapter) =>\n  Boolean(adapter.connection) && adapter.connection.readyState === 1","tryCatchPattern":"try { await payload.db.beginTransaction() }\ncatch (e) { if (/no connection to the database/.test(e.message)) await waitForDb(payload) else throw e }","preventionTips":["Await payload.init() before serving requests.","In serverless, reuse the connection; do not disconnect between invocations.","Add a readiness check that verifies connection.readyState === 1."],"tags":["mongodb","connection","transactions","startup","serverless"],"backgroundTag":null,"analyzedSha":"00c58b35c0ed348ddc22daabf467b139727214fd","analyzedAt":"2026-08-12T20:45:03.758Z","schemaVersion":2},"datasetVersion":"2026-08-12T23:17:12.415Z"}