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 MongoParseError (constant LB_REPLICA_SET_ERROR) at src/connection_string.ts:574 when `loadBalanced=true` and `replicaSet` is also set. A load-balanced topology deliberately hides the backend topology behind one endpoint, so naming a replica set contradicts that model.

Solutions

  1. Remove `replicaSet` from the URI and options when running in loadBalanced mode.
  2. If you actually want replica-set semantics, remove `loadBalanced`.

Example fix

// before
new MongoClient('mongodb://host:27017/?loadBalanced=true&replicaSet=rs0')

// after
new MongoClient('mongodb://host:27017/?loadBalanced=true')
Defensive patterns

Strategy: validation

Validate before calling

function assertNoLbPlusRs(options = {}, uri = '') {
  const lb = options.loadBalanced ?? /loadBalanced=true/i.test(uri);
  const rs = options.replicaSet ?? uri.match(/replicaSet=([^&]+)/i)?.[1];
  if (lb && rs) throw new Error('loadBalanced and replicaSet cannot both be set.');
}

Try / catch

try { new MongoClient(uri, options); } catch (e) { if (e instanceof MongoParseError && /loadBalanced option not supported with a replicaSet/.test(e.message)) { delete options.replicaSet; } else throw e; }

Prevention

When it happens

Trigger: `mongodb://host:27017/?loadBalanced=true&replicaSet=rs0`, or options `{ loadBalanced: true, replicaSet: 'rs0' }`.

Common situations: Migrating from a replica-set URI to a load-balanced LB/mongos endpoint and forgetting to drop the replicaSet option; shared config object that always sets replicaSet.

Related errors


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

Appendix: 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 dce7939f86)