mongodb/node-mongodb-native · error · MongoInvalidArgumentError

Invalid sort format: ${JSON.stringify(sort)} Sort must be a

Error message

Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object

What it means

Thrown by formatSort() when the sort argument is non-null, not a string, and not an object (typeof !== 'object'). This covers primitives like numbers, booleans, or symbols passed where a sort spec is expected. It is a MongoInvalidArgumentError; the JSON.stringify of the offending value is included.

Source

Thrown at src/sort.ts:127

function mapToMap(t: ReadonlyMap<string, SortDirection>): SortForCmd {
  const sortEntries: SortPairForCmd[] = Array.from(t).map(([k, v]) => [
    `${k}`,
    prepareDirection(v)
  ]);
  return new Map(sortEntries);
}

/** converts a Sort type into a type that is valid for the server (SortForCmd) */
export function formatSort(
  sort: Sort | undefined,
  direction?: SortDirection
): SortForCmd | undefined {
  if (sort == null) return undefined;

  if (typeof sort === 'string') return new Map([[sort, prepareDirection(direction)]]); // 'fieldName'

  if (typeof sort !== 'object') {
    throw new MongoInvalidArgumentError(
      `Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`
    );
  }

  if (!isReadonlyArray(sort)) {
    if (isMap(sort)) return mapToMap(sort); // Map<fieldName, SortDirection>
    if (Object.keys(sort).length) return objectToMap(sort); // { [fieldName: string]: SortDirection }
    return undefined;
  }
  if (!sort.length) return undefined;
  if (isDeep(sort)) return deepToMap(sort); // [ [fieldName, sortDir], [fieldName, sortDir] ... ]
  if (isPair(sort)) return pairToMap(sort); // [ fieldName, sortDir ]
  return stringsToMap(sort); // [ fieldName, fieldName ]
}

View on GitHub (pinned to 3366c21a63)

Solutions

  1. Pass a valid sort spec: an object ({ field: 1 }), a string ('field'), or an array (['field', [ ['field', -1] ]]).
  2. If you meant to sort one field, use .sort('field', 1) (string + direction) or .sort({ field: 1 }).
  3. Validate the dynamic sort value's type before passing it to .sort().

Example fix

// before
await coll.find().sort(1).toArray(); // throws: Invalid sort format

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

Strategy: type-guard

Validate before calling

function isValidSortShape(s: unknown): boolean {
  return (
    s == null ||
    typeof s === 'string' ||
    (typeof s === 'object' && !Array.isArray(s)) ||
    Array.isArray(s)
  ) && typeof s !== 'number' && typeof s !== 'boolean';
}
if (isValidSortShape(sortVal)) {
  await coll.find().sort(sortVal).toArray();
}

Type guard

import type { Sort } from 'mongodb';
function isSort(v: unknown): v is Sort {
  return typeof v === 'string' || (typeof v === 'object' && v !== null);
}

Try / catch

try {
  await coll.find().sort(sortVal as any).toArray();
} catch (e) {
  if (e instanceof MongoInvalidArgumentError && /Invalid sort format/.test(e.message)) {
    // rebuild sort as an object and retry
  } else throw e;
}

Prevention

When it happens

Trigger: Calling .sort(123), .sort(true), .sort(false), or .sort(Symbol()) on a cursor/find. Also .sort() with a variable that holds a non-object, non-string value at runtime.

Common situations: Passing a numeric flag (e.g. 1) directly to .sort() intending it as a direction; wrong-arity call like .sort(field, 1) when field is undefined leaves sort=undefined then 1 is passed as a primitive; config-driven sort where the value resolves to a number.

Related errors


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