mongodb/node-mongodb-native · error · MongoInvalidArgumentError

Stream end (${options.end}) must not be more than the length

Error message

Stream end (${options.end}) must not be more than the length of the file (${doc.length})

What it means

handleEndOption validates that the requested end offset does not exceed the file's length. An end past EOF is rejected to keep the byte math consistent.

Source

Thrown at src/gridfs/download.ts:466

    }

    stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize;
    stream.s.expected = Math.floor(options.start / doc.chunkSize);

    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. Clamp end with Math.min(end, file.length) using the file document's length
  2. Look up the file length before opening the stream
  3. Validate user-supplied ranges against the actual file size

Example fix

// before
{ end: requestedEnd }
// after
{ end: Math.min(requestedEnd, file.length) }
Defensive patterns

Strategy: validation

Validate before calling

async function clampEnd(bucket, id, desired) {
  const file = await bucket.find({ _id: id }).next();
  return Math.min(desired, file?.length ?? 0);
}

Prevention

When it happens

Trigger: bucket.openDownloadStream(id, { end: file.length + 50 }) when the file is shorter than expected.

Common situations: Off-by-one; stale length assumption; using end as an exclusive bound against a truncated file.

Related errors


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