{"record":{"id":"5fc283c5ed2433ee","repo":"mongodb/node-mongodb-native","slug":"read-preference-in-a-transaction-must-be-primary","errorCode":null,"errorMessage":"Read preference in a transaction must be primary, not: ${readPreference.mode}","messagePattern":"Read preference in a transaction must be primary, not: (.+?)","errorType":"exception","errorClass":"MongoTransactionError","httpStatus":null,"severity":"error","filePath":"src/operations/execute_operation.ts","lineNumber":110,"sourceCode":"  ) {\n    throw new MongoCompatibilityError('Snapshot reads require MongoDB 5.0 or later');\n  } else if (session.client !== client) {\n    throw new MongoInvalidArgumentError('ClientSession must be from the same MongoClient');\n  }\n\n  operation.session ??= session;\n\n  const readPreference = operation.readPreference ?? ReadPreference.primary;\n  const inTransaction = !!session?.inTransaction();\n\n  const hasReadAspect = operation.hasAspect(Aspect.READ_OPERATION);\n\n  if (\n    inTransaction &&\n    !readPreference.equals(ReadPreference.primary) &&\n    (hasReadAspect || operation.commandName === 'runCommand')\n  ) {\n    throw new MongoTransactionError(\n      `Read preference in a transaction must be primary, not: ${readPreference.mode}`\n    );\n  }\n\n  if (session?.isPinned && session.transaction.isCommitted && !operation.bypassPinningCheck) {\n    session.unpin();\n  }\n\n  timeoutContext ??= TimeoutContext.create({\n    session,\n    serverSelectionTimeoutMS: client.s.options.serverSelectionTimeoutMS,\n    waitQueueTimeoutMS: client.s.options.waitQueueTimeoutMS,\n    timeoutMS: operation.options.timeoutMS\n  });\n\n  try {\n    return await executeOperationWithRetries(operation, {\n      topology,","sourceCodeStart":92,"sourceCodeEnd":128,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/operations/execute_operation.ts#L92-L128","documentation":"Thrown when an operation inside an active transaction uses a read preference other than primary. MongoDB transactions must read from the primary (except when the transaction has been pinned to a mongos after a sharded operation, which the driver handles internally), so the driver rejects secondary/nearest/secondaryPreferred before sending the command.","triggerScenarios":"Calling collection.find({}, { session, readPreference: 'secondary' }) while session.inTransaction() is true. Also from setting a non-primary read preference on the collection or client and then running operations inside a transaction.","commonSituations":"Read-heavy analytics that default to secondary reads but accidentally run inside a withTransaction block; read preference inherited from the URI (&readPreference=secondary) conflicting with transactional writes.","solutions":["Inside withTransaction, let the driver use primary by default — do not override readPreference on individual operations.","If you set readPreference at the client or collection level, override it to 'primary' for operations within the transaction.","For read-only workloads that don't need transactional multi-document atomicity, consider running outside a transaction with the secondary read preference."],"exampleFix":"// before\nawait session.withTransaction(async () => {\n  await collection.find({}, { session, readPreference: 'secondary' }).next();\n});\n\n// after\nawait session.withTransaction(async () => {\n  await collection.find({}, { session }).next(); // primary by default\n});","handlingStrategy":"validation","validationCode":"if (session?.inTransaction() && readPreference && readPreference !== 'primary') {\n  throw new Error('Read preference inside a transaction must be primary');\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Do not set readPreference on operations inside withTransaction.","Audit collection/client-level readPreference defaults before entering a transaction."],"tags":["transactions","read-preference","api-misuse"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}