mongodb/node-mongodb-native · error · MongoInvalidArgumentError

End option must be defined

Error message

End option must be defined

What it means

handleEndOption (src/gridfs/download.ts:482) is a defensive internal guard that throws 'End option must be defined' when the helper is reached without an end value. Like error 269, this is an internal invariant; normal user calls provide end explicitly or omit it (in which case the helper is not invoked). Encountering it suggests internal misuse or a mutated options object.

Solutions

  1. Do not subclass or mutate stream internals; provide end via openDownloadStream(id, { end }).
  2. If reached through a supported path, ensure the options object always includes end when range reading is intended.
Defensive patterns

Strategy: validation

Validate before calling

// Internal guard. Do not subclass GridFSBucketReadStream.
// Provide end via openDownloadStream options.
function openSafeEnd(bucket, id, range) {
  if (!range || range.end == null) return bucket.openDownloadStream(id);
  return bucket.openDownloadStream(id, range);
}

Type guard

function hasEnd(range: unknown): range is { end: number } {
  return range != null && typeof (range as any).end === 'number';
}

Prevention

When it happens

Trigger: Internal/custom subclass invoking handleEndOption without an end value. Mutation of the stream options object removing end between construction and initialization.

Common situations: Rare for end users; appears only with subclassing or direct manipulation of GridFSBucketReadStream internals.

Related errors


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

Appendix: source

Thrown at src/gridfs/download.ts:482

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