mongodb/node-mongodb-native · error · MongoParseError
can only be a positive int value, got
Error message
${name} can only be a positive int value, got: ${value} What it means
Unsigned-int options (srvMaxHosts and similar) accept any integer but reject negatives. getUIntFromOptions calls getIntFromOptions then checks for <0 and throws, including the original value in the message.
Solutions
- Use 0 (or omit the option) to disable srvMaxHosts.
- Pass a positive integer to cap the number of hosts.
Example fix
// before
new MongoClient('mongodb+srv://h/db?srvMaxHosts=-1');
// after
new MongoClient('mongodb+srv://h/db?srvMaxHosts=0'); Defensive patterns
Strategy: validation
Validate before calling
function assertUIntOption(name: string, value: unknown) {
assertIntOption(name, value);
if (Number(value) < 0) throw new Error(`${name} must be >= 0, got: ${value}`);
} Prevention
- Use 0 as the 'disable' sentinel for unsigned options, never -1.
- Validate numeric config at the boundary where it enters your app.
When it happens
Trigger: Passing a negative integer to an unsigned option, e.g. 'srvMaxHosts=-1' in the URI or srvMaxHosts: -1 in options.
Common situations: Using -1 as a 'disable' sentinel the way some other libraries do, or arithmetic that underflows.
Related errors
- Expected to be stringified int value, got
- All values of tls/ssl must be the same.
- Auth mechanism property ALLOWED_HOSTS is not allowed in the…
- authMechanism requires an authSource of '$external
- Cannot combine replicaSet option with srvMaxHosts
AI-assisted analysis of mongodb/node-mongodb-native@dce7939f86 (2026-08-11).
Data as JSON: /api/errors/2217379d9eff4670.
Report an issue: GitHub.
Appendix: source
Thrown at src/connection_string.ts:199
case 'false':
return false;
default:
throw new MongoParseError(`${name} must be either "true" or "false"`);
}
}
function getIntFromOptions(name: string, value: unknown): number {
const parsedInt = parseInteger(value);
if (parsedInt != null) {
return parsedInt;
}
throw new MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`);
}
function getUIntFromOptions(name: string, value: unknown): number {
const parsedValue = getIntFromOptions(name, value);
if (parsedValue < 0) {
throw new MongoParseError(`${name} can only be a positive int value, got: ${value}`);
}
return parsedValue;
}
function* entriesFromString(value: string): Generator<[string, string]> {
if (value === '') {
return;
}
const keyValuePairs = value.split(',');
for (const keyValue of keyValuePairs) {
const [key, value] = keyValue.split(/:(.*)/);
if (value == null) {
throw new MongoParseError('Cannot have undefined values in key value pairs');
}
yield [key, value];
}
}View on GitHub (pinned to dce7939f86)