mongodb/node-mongodb-native · error · MongoInvalidArgumentError

Stream end (${options.end}) must not be negative

Error message

Stream end (${options.end}) must not be negative

What it means

Despite the wording, handleEndOption throws this when end is set but start is null OR start is negative. The guard runs while validating the end option, so the error is surfaced in terms of end. Provide a non-negative start whenever you set end.

Source

Thrown at src/gridfs/download.ts:471

    return options.start - stream.s.bytesRead;
  }
  throw new MongoInvalidArgumentError('Start option must be defined');
}

function handleEndOption(
  stream: GridFSBucketReadStream,
  doc: Document,
  cursor: FindCursor<GridFSChunk>,
  options: GridFSBucketReadStreamOptions
) {
  if (options && options.end != null) {
    if (options.end > doc.length) {
      throw new MongoInvalidArgumentError(
        `Stream end (${options.end}) must not be more than the length of the file (${doc.length})`
      );
    }
    if (options.start == null || options.start < 0) {
      throw new MongoInvalidArgumentError(`Stream end (${options.end}) must not be negative`);
    }

    const start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0;

    cursor.limit(Math.ceil(options.end / doc.chunkSize) - start);

    stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize);

    return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end;
  }
  throw new MongoInvalidArgumentError('End option must be defined');
}

View on GitHub (pinned to 3366c21a63)

Solutions

  1. Always pass a non-negative start when you set end (use start: 0 if you want the whole prefix)
  2. Validate start >= 0 before opening the stream
  3. Treat { start, end } as a required pair

Example fix

// before
bucket.openDownloadStream(id, { end: 100 });
// after
bucket.openDownloadStream(id, { start: 0, end: 100 });
Defensive patterns

Strategy: validation

Validate before calling

if (options.end != null) {
  options.start = Math.max(0, options.start ?? 0);
}

Prevention

When it happens

Trigger: bucket.openDownloadStream(id, { end: 100 }) with no start, or with start: -1.

Common situations: Setting an upper bound without a lower bound; negative start leaking into end validation; partial range config.

Related errors


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