mongodb/node-mongodb-native · error · MongoParseError

loadBalanced option not supported with a replicaSet option

Error message

loadBalanced option not supported with a replicaSet option

What it means

Thrown by validateLoadBalancedOptions (connection_string.ts:573-575) when both loadBalanced=true and a replicaSet name are provided. Load-balanced topology hides individual servers behind a single endpoint, while replicaSet requires direct member awareness for elections; the combination is invalid.

Source

Thrown at src/connection_string.ts:574

 * #### Throws if LB mode is true:
 * - hosts contains more than one host
 * - there is a replicaSet name set
 * - directConnection is set
 * - if srvMaxHosts is used when an srv connection string is passed in
 *
 * @throws MongoParseError
 */
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[]
) {

View on GitHub (pinned to 3366c21a63)

Solutions

  1. Remove the replicaSet option when using loadBalanced.
  2. Or remove loadBalanced if you intend to connect directly to the replica set.
  3. Pick one topology model and align all options to it.

Example fix

// before
const c = new MongoClient('mongodb://lb.example/?loadBalanced=true&replicaSet=rs0');
// after
const c = new MongoClient('mongodb://lb.example/?loadBalanced=true');
Defensive patterns

Strategy: validation

Validate before calling

const lb = new URL(uri).searchParams.get('loadBalanced') === 'true' || opts.loadBalanced === true;
const hasRS = Boolean(opts.replicaSet ?? new URL(uri).searchParams.get('replicaSet'));
if (lb && hasRS) throw new Error('loadBalanced and replicaSet are mutually exclusive');

Prevention

When it happens

Trigger: URI like 'mongodb://lb.example/?loadBalanced=true&replicaSet=rs0' or options { replicaSet: 'rs0' } combined with a loadBalanced URI.

Common situations: Migrating from a replica-set URI to a load-balanced deployment and leaving the replicaSet parameter; Atlas-style templated config that injects replicaSet by default.

Related errors


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