mongodb/node-mongodb-native · error · MongoParseError

loadBalanced is only a valid option in the URI

Error message

loadBalanced is only a valid option in the URI

What it means

loadBalanced is a topology property baked into the URI per the load-balancer spec; it must be set there (e.g. '?loadBalanced=true') so all clients sharing the URI see the same topology. Passing it via the options object is rejected because it would let per-client code disagree with the URI.

Solutions

  1. Move loadBalanced into the URI query string.
  2. Remove the loadBalanced key from the options object.

Example fix

// before
new MongoClient('mongodb://h/db', { loadBalanced: true });
// after
new MongoClient('mongodb://h/db?loadBalanced=true');
Defensive patterns

Strategy: validation

Validate before calling

function assertLoadBalancedNotInOptions(opts: Record<string, unknown>) {
  if ('loadBalanced' in opts) {
    throw new Error('Set loadBalanced in the URI (?loadBalanced=true), not the options object');
  }
}

Prevention

When it happens

Trigger: Calling new MongoClient(uri, { loadBalanced: true }) (or false). Detected via objectOptions.has('loadBalanced').

Common situations: Configuring a load-balanced deployment in code rather than the URI, often because the URI is shared across services.

Related errors


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

Appendix: source

Thrown at src/connection_string.ts:330

  if (urlOptions.has('serverApi')) {
    throw new MongoParseError(
      'URI cannot contain `serverApi`, it can only be passed to the client'
    );
  }

  const uriMechanismProperties = urlOptions.get('authMechanismProperties');
  if (uriMechanismProperties) {
    for (const property of uriMechanismProperties) {
      if (/(^|,)ALLOWED_HOSTS:/.test(property as string)) {
        throw new MongoParseError(
          'Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.'
        );
      }
    }
  }

  if (objectOptions.has('loadBalanced')) {
    throw new MongoParseError('loadBalanced is only a valid option in the URI');
  }

  // All option collection

  const allProvidedOptions = new CaseInsensitiveMap<unknown[]>();

  const allProvidedKeys = new Set<string>([...urlOptions.keys(), ...objectOptions.keys()]);

  for (const key of allProvidedKeys) {
    const values = [];
    const objectOptionValue = objectOptions.get(key);
    if (objectOptionValue != null) {
      values.push(objectOptionValue);
    }

    const urlValues = urlOptions.get(key) ?? [];
    values.push(...urlValues);
    allProvidedOptions.set(key, values);

View on GitHub (pinned to dce7939f86)