mongodb/node-mongodb-native · error · MongoParseError

Cannot limit srv hosts with loadBalanced enabled

Error message

Cannot limit srv hosts with loadBalanced enabled

What it means

Thrown by validateLoadBalancedOptions (connection_string.ts:580-582) for an SRV URI when loadBalanced=true and srvMaxHosts > 0. loadBalanced requires connecting to all SRV-resolved endpoints behind the load balancer; limiting hosts via srvMaxHosts would break the LB topology assumption.

Source

Thrown at src/connection_string.ts:581

 */
function validateLoadBalancedOptions(
  hosts: HostAddress[] | string[],
  mongoOptions: MongoOptions,
  isSrv: boolean
): void {
  if (mongoOptions.loadBalanced) {
    if (hosts.length > 1) {
      throw new MongoParseError(LB_SINGLE_HOST_ERROR);
    }
    if (mongoOptions.replicaSet) {
      throw new MongoParseError(LB_REPLICA_SET_ERROR);
    }
    if (mongoOptions.directConnection) {
      throw new MongoParseError(LB_DIRECT_CONNECTION_ERROR);
    }

    if (isSrv && mongoOptions.srvMaxHosts > 0) {
      throw new MongoParseError('Cannot limit srv hosts with loadBalanced enabled');
    }
  }
  return;
}

function setOption(
  mongoOptions: any,
  key: string,
  descriptor: OptionDescriptor,
  values: unknown[]
) {
  const { target, type, transform } = descriptor;
  const name = target ?? key;

  switch (type) {
    case 'boolean':
      mongoOptions[name] = getBoolean(name, values[0]);
      break;

View on GitHub (pinned to 3366c21a63)

Solutions

  1. Set srvMaxHosts=0 (the default) when using loadBalanced.
  2. Or remove loadBalanced if you want srvMaxHosts-based randomization.
  3. Confirm your deployment is actually behind a load balancer before enabling loadBalanced.

Example fix

// before
const c = new MongoClient('mongodb+srv://cluster.example/?loadBalanced=true&srvMaxHosts=2');
// after
const c = new MongoClient('mongodb+srv://cluster.example/?loadBalanced=true');
Defensive patterns

Strategy: validation

Validate before calling

const isSRV = uri.startsWith('mongodb+srv://');
const lb = new URL(uri).searchParams.get('loadBalanced') === 'true' || opts.loadBalanced === true;
const srvMaxHosts = Number(opts.srvMaxHosts ?? new URL(uri).searchParams.get('srvMaxHosts') ?? 0);
if (isSRV && lb && srvMaxHosts > 0) throw new Error('loadBalanced requires srvMaxHosts=0');

Prevention

When it happens

Trigger: URI like 'mongodb+srv://cluster.example/?loadBalanced=true&srvMaxHosts=2'.

Common situations: Adding srvMaxHosts to control fan-out on a load-balanced deployment; combining 'limit hosts' and 'load balanced' best-practice snippets.

Related errors


AI-assisted analysis of mongodb/node-mongodb-native@3366c21a63 (2026-08-04). Data as JSON: /data/errors/3840326523192585.json. Report an issue: GitHub.