{"id":"c0110101d077b9cd","repo":"mongodb/node-mongodb-native","slug":"invalid-sort-format-json-stringify-sort-sort","errorCode":null,"errorMessage":"Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object","messagePattern":"Invalid sort format: (.+?) Sort must be a valid object","errorType":"exception","errorClass":"MongoInvalidArgumentError","httpStatus":null,"severity":"error","filePath":"src/sort.ts","lineNumber":127,"sourceCode":"function mapToMap(t: ReadonlyMap<string, SortDirection>): SortForCmd {\n  const sortEntries: SortPairForCmd[] = Array.from(t).map(([k, v]) => [\n    `${k}`,\n    prepareDirection(v)\n  ]);\n  return new Map(sortEntries);\n}\n\n/** converts a Sort type into a type that is valid for the server (SortForCmd) */\nexport function formatSort(\n  sort: Sort | undefined,\n  direction?: SortDirection\n): SortForCmd | undefined {\n  if (sort == null) return undefined;\n\n  if (typeof sort === 'string') return new Map([[sort, prepareDirection(direction)]]); // 'fieldName'\n\n  if (typeof sort !== 'object') {\n    throw new MongoInvalidArgumentError(\n      `Invalid sort format: ${JSON.stringify(sort)} Sort must be a valid object`\n    );\n  }\n\n  if (!isReadonlyArray(sort)) {\n    if (isMap(sort)) return mapToMap(sort); // Map<fieldName, SortDirection>\n    if (Object.keys(sort).length) return objectToMap(sort); // { [fieldName: string]: SortDirection }\n    return undefined;\n  }\n  if (!sort.length) return undefined;\n  if (isDeep(sort)) return deepToMap(sort); // [ [fieldName, sortDir], [fieldName, sortDir] ... ]\n  if (isPair(sort)) return pairToMap(sort); // [ fieldName, sortDir ]\n  return stringsToMap(sort); // [ fieldName, fieldName ]\n}\n","sourceCodeStart":109,"sourceCodeEnd":142,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/sort.ts#L109-L142","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Pass a valid sort spec: an object ({ field: 1 }), a string ('field'), or an array (['field', [ ['field', -1] ]]).","If you meant to sort one field, use .sort('field', 1) (string + direction) or .sort({ field: 1 }).","Validate the dynamic sort value's type before passing it to .sort()."],"exampleFix":"// before\nawait coll.find().sort(1).toArray(); // throws: Invalid sort format\n\n// after\nawait coll.find().sort({ _id: 1 }).toArray();","handlingStrategy":"type-guard","validationCode":"function isValidSortShape(s: unknown): boolean {\n  return (\n    s == null ||\n    typeof s === 'string' ||\n    (typeof s === 'object' && !Array.isArray(s)) ||\n    Array.isArray(s)\n  ) && typeof s !== 'number' && typeof s !== 'boolean';\n}\nif (isValidSortShape(sortVal)) {\n  await coll.find().sort(sortVal).toArray();\n}","typeGuard":"import type { Sort } from 'mongodb';\nfunction isSort(v: unknown): v is Sort {\n  return typeof v === 'string' || (typeof v === 'object' && v !== null);\n}","tryCatchPattern":"try {\n  await coll.find().sort(sortVal as any).toArray();\n} catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /Invalid sort format/.test(e.message)) {\n    // rebuild sort as an object and retry\n  } else throw e;\n}","preventionTips":["Always pass an object ({ field: 1 }) or string ('field') to .sort().","Validate dynamically-built sort values are objects or strings before use.","Add TypeScript types on sort variables so the compiler rejects primitives."],"tags":["sort","find","invalid-argument","query","type-error"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}