mongodb/node-mongodb-native · error · MongoInvalidArgumentError

Invalid sort direction: ${JSON.stringify(direction)}

Error message

Invalid sort direction: ${JSON.stringify(direction)}

What it means

Thrown by the internal prepareDirection() helper used by formatSort when a sort direction value cannot be normalized. Accepted values are 1, -1, 'asc', 'desc', 'ascending', 'descending' (case-insensitive), and { $meta: string }. Anything else, after coercion to a lowercase string, lands in the default switch branch and throws MongoInvalidArgumentError.

Source

Thrown at src/sort.ts:48

/** @internal */
type SortPairForCmd = [string, SortDirectionForCmd];

/** @internal */
function prepareDirection(direction: any = 1): SortDirectionForCmd {
  const value = `${direction}`.toLowerCase();
  if (isMeta(direction)) return direction;
  switch (value) {
    case 'ascending':
    case 'asc':
    case '1':
      return 1;
    case 'descending':
    case 'desc':
    case '-1':
      return -1;
    default:
      throw new MongoInvalidArgumentError(`Invalid sort direction: ${JSON.stringify(direction)}`);
  }
}

/** @internal */
function isMeta(t: SortDirection): t is { $meta: string } {
  return typeof t === 'object' && t != null && '$meta' in t && typeof t.$meta === 'string';
}

/** @internal */
function isPair(t: Sort): t is readonly [string, SortDirection] {
  if (Array.isArray(t) && t.length === 2) {
    try {
      prepareDirection(t[1]);
      return true;
    } catch {
      return false;
    }
  }

View on GitHub (pinned to 3366c21a63)

Solutions

  1. Use one of the accepted literals: 1/-1 or 'asc'/'desc'.
  2. Validate user-supplied direction against an allowlist before building the sort spec.
  3. For text-score sorts use { $meta: 'textScore' }.

Example fix

// before
await coll.find().sort({ score: 'up' }).toArray(); // throws

// after
await coll.find().sort({ score: -1 }).toArray();
Defensive patterns

Strategy: validation

Validate before calling

const ALLOWED = new Set([1, -1, 'asc', 'desc', 'ascending', 'descending']);
function isValidDirection(d: unknown): boolean {
  return (
    ALLOWED.has(d as any) ||
    (d != null && typeof d === 'object' && typeof (d as any).$meta === 'string')
  );
}
if (Object.values(sortSpec).every(isValidDirection)) {
  await coll.find().sort(sortSpec).toArray();
}

Type guard

import type { SortDirection } from 'mongodb';
function isSortDirection(v: unknown): v is SortDirection {
  return [1, -1, 'asc', 'desc', 'ascending', 'descending'].includes(v as any) ||
    (v != null && typeof v === 'object' && typeof (v as any).$meta === 'string');
}

Try / catch

try {
  await coll.find().sort(sortSpec).toArray();
} catch (e) {
  if (e instanceof MongoInvalidArgumentError && /Invalid sort direction/.test(e.message)) {
    // coerce unknown directions to 1/-1 and retry
  } else throw e;
}

Prevention

When it happens

Trigger: Passing an invalid direction in a sort spec, e.g. { x: 'up' }, { x: 0 }, { x: 2 }, { x: true }, or a typo like { x: 'ascc' }. Also reachable via collection.find().sort('field', 'horizontal').

Common situations: Typos in sort direction strings; building sort specs dynamically from user input without validation; numeric values other than 1/-1; legacy code assuming 'up'/'down' work.

Related errors


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