mongodb/node-mongodb-native · error · MongoInvalidArgumentError

Invalid read preference specified

Error message

Invalid read preference specified

What it means

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.

Solutions

  1. Construct ReadPreference through the constructor or static instances rather than fromString for untrusted input.
  2. Validate the mode against the five canonical values before use.
  3. Do not mutate ReadPreference instances after construction.

Example fix

// before
const rp = ReadPreference.fromString('secondary-only');
// after
const rp = ReadPreference.secondary;
Defensive patterns

Strategy: type-guard

Validate before calling

const VALID_MODES = new Set(['primary','primaryPreferred','secondary','secondaryPreferred','nearest']);
function safeRP(mode) {
  if (!VALID_MODES.has(mode)) throw new Error(`invalid mode: ${mode}`);
  return new ReadPreference(mode);
}

Type guard

function isValidReadPreference(rp): boolean {
  return rp instanceof ReadPreference && ReadPreference.isValid(rp.mode);
}

Try / catch

try {
  await collection.findOne({}, { readPreference });
} catch (e) {
  if (e instanceof MongoInvalidArgumentError && /Invalid read preference specified/.test(e.message)) {
    // fall back to a known-good ReadPreference
  }
  throw e;
}

Prevention

When it happens

Trigger: 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.

Common situations: User-supplied mode strings passed through ReadPreference.fromString without validation, or buggy code mutating a shared ReadPreference instance.

Related errors


AI-assisted analysis of mongodb/node-mongodb-native@dce7939f86 (2026-08-11). Data as JSON: /api/errors/cccdfec9bad54362. Report an issue: GitHub.

Appendix: source

Thrown at src/sdam/server_selection.ts:385

    }

    default: {
      const _exhaustiveCheck: never = mode;
      throw new MongoRuntimeError(
        `unexpected readPreference=${mode} (should never happen).  Please report a bug in the Node driver Jira project.`
      );
    }
  }
}

/**
 * Returns a function which selects servers based on a provided read preference
 *
 * @param readPreference - The read preference to select with
 */
export function readPreferenceServerSelector(readPreference: ReadPreference): ServerSelector {
  if (!readPreference.isValid()) {
    throw new MongoInvalidArgumentError('Invalid read preference specified');
  }

  return function readPreferenceServers(
    topologyDescription: TopologyDescription,
    servers: ServerDescription[],
    deprioritized: DeprioritizedServers
  ): ServerDescription[] {
    switch (topologyDescription.type) {
      case 'Single':
        return latencyWindowReducer(topologyDescription, servers.filter(knownFilter));
      case 'ReplicaSetNoPrimary':
      case 'ReplicaSetWithPrimary':
        return secondarySelector(readPreference, topologyDescription, servers, deprioritized);
      case 'Sharded': {
        const selectable = filterDeprioritized(servers, deprioritized);
        return latencyWindowReducer(topologyDescription, selectable.filter(knownFilter));
      }
      case 'Unknown':

View on GitHub (pinned to dce7939f86)