{"record":{"id":"cccdfec9bad54362","repo":"mongodb/node-mongodb-native","slug":"invalid-read-preference-specified","errorCode":null,"errorMessage":"Invalid read preference specified","messagePattern":"Invalid read preference specified","errorType":"exception","errorClass":"MongoInvalidArgumentError","httpStatus":null,"severity":"error","filePath":"src/sdam/server_selection.ts","lineNumber":385,"sourceCode":"    }\n\n    default: {\n      const _exhaustiveCheck: never = mode;\n      throw new MongoRuntimeError(\n        `unexpected readPreference=${mode} (should never happen).  Please report a bug in the Node driver Jira project.`\n      );\n    }\n  }\n}\n\n/**\n * Returns a function which selects servers based on a provided read preference\n *\n * @param readPreference - The read preference to select with\n */\nexport function readPreferenceServerSelector(readPreference: ReadPreference): ServerSelector {\n  if (!readPreference.isValid()) {\n    throw new MongoInvalidArgumentError('Invalid read preference specified');\n  }\n\n  return function readPreferenceServers(\n    topologyDescription: TopologyDescription,\n    servers: ServerDescription[],\n    deprioritized: DeprioritizedServers\n  ): ServerDescription[] {\n    switch (topologyDescription.type) {\n      case 'Single':\n        return latencyWindowReducer(topologyDescription, servers.filter(knownFilter));\n      case 'ReplicaSetNoPrimary':\n      case 'ReplicaSetWithPrimary':\n        return secondarySelector(readPreference, topologyDescription, servers, deprioritized);\n      case 'Sharded': {\n        const selectable = filterDeprioritized(servers, deprioritized);\n        return latencyWindowReducer(topologyDescription, selectable.filter(knownFilter));\n      }\n      case 'Unknown':","sourceCodeStart":367,"sourceCodeEnd":403,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/dce7939f86fb283e167ad709955abedb7bf23124/src/sdam/server_selection.ts#L367-L403","documentation":"Thrown by readPreferenceServerSelector() (src/sdam/server_selection.ts:385) as MongoInvalidArgumentError when the supplied ReadPreference's isValid() returns false. Unlike the static isValid that accepts the five canonical modes or null, this instance check validates the read preference object's own mode. It guards server selection from an internally-constructed or mutated invalid ReadPreference.","triggerScenarios":"A ReadPreference constructed via fromString with an invalid mode (fromString does not validate), or a ReadPreference whose mode was mutated to an invalid value after construction. Reached during any read operation that triggers server selection.","commonSituations":"User-supplied mode strings passed through ReadPreference.fromString without validation, or buggy code mutating a shared ReadPreference instance.","solutions":["Construct ReadPreference through the constructor or static instances rather than fromString for untrusted input.","Validate the mode against the five canonical values before use.","Do not mutate ReadPreference instances after construction."],"exampleFix":"// before\nconst rp = ReadPreference.fromString('secondary-only');\n// after\nconst rp = ReadPreference.secondary;","handlingStrategy":"type-guard","validationCode":"const VALID_MODES = new Set(['primary','primaryPreferred','secondary','secondaryPreferred','nearest']);\nfunction safeRP(mode) {\n  if (!VALID_MODES.has(mode)) throw new Error(`invalid mode: ${mode}`);\n  return new ReadPreference(mode);\n}","typeGuard":"function isValidReadPreference(rp): boolean {\n  return rp instanceof ReadPreference && ReadPreference.isValid(rp.mode);\n}","tryCatchPattern":"try {\n  await collection.findOne({}, { readPreference });\n} catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /Invalid read preference specified/.test(e.message)) {\n    // fall back to a known-good ReadPreference\n  }\n  throw e;\n}","preventionTips":["Avoid ReadPreference.fromString for untrusted input; use the constructor or static instances.","Never mutate a ReadPreference's mode after construction.","Validate read-preference objects at the boundary of your data flow."],"tags":["read-preference","server-selection","validation","invalid-argument"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}