{"record":{"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/dce7939f86fb283e167ad709955abedb7bf23124/src/sort.ts#L109-L142","documentation":"Thrown by formatSort() when the sort argument is not null/undefined, not a string, and not an object. The Sort type union expects a string, array, Map, or plain object; a primitive like a number or boolean fails the typeof checks and raises a MongoInvalidArgumentError. The invalid value is JSON-stringified in the message.","triggerScenarios":"Calling .sort(42), .sort(true), or .sort(NaN) directly. Also reachable when a variable typed loosely (any) holds a primitive and is passed as the sort argument without prior validation.","commonSituations":"Code that constructs sort parameters dynamically and accidentally passes a scalar (e.g. a parsed numeric from config) instead of an object. TypeScript users typically catch this at compile time, so runtime hits occur in JS codebases or when using `any`.","solutions":["Pass a valid Sort shape: an object like { field: 1 }, an array like [['field', 1]], a Map, or a string field name.","If the sort value is dynamic, validate it is a string or object before calling .sort().","Remove `any` typing on the sort variable so TypeScript flags the misuse at compile time."],"exampleFix":"// before\nconst sort = config.sortValue; // number 42\ncollection.find().sort(sort);\n\n// after\nconst sort = config.sortValue ?? {};\ncollection.find().sort(typeof sort === 'object' ? sort : { _id: 1 });","handlingStrategy":"type-guard","validationCode":"function isSortable(v: unknown): v is string | object {\n  return v == null || typeof v === 'string' || typeof v === 'object';\n}\nconst safeSort = isSortable(userSort) ? userSort : undefined;","typeGuard":"function isSortInput(v: unknown): v is string | Record<string, unknown> | unknown[] | Map<string, unknown> {\n  return v == null || typeof v === 'string' || (typeof v === 'object' && !Array.isArray(v) || Array.isArray(v));\n}","tryCatchPattern":"try {\n  await collection.find().sort(sortValue as any).toArray();\n} catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /Invalid sort format/.test(e.message)) {\n    await collection.find().toArray(); // no sort\n  } else throw e;\n}","preventionTips":["Avoid `any` typing on sort variables so TypeScript enforces the Sort union at compile time.","Validate dynamically-built sort values are objects/arrays/strings before calling .sort().","Default to undefined when the sort input is of an unexpected type."],"tags":["sort","query","validation","crud"],"backgroundTag":null,"analyzedSha":"dce7939f86fb283e167ad709955abedb7bf23124","analyzedAt":"2026-08-11T04:54:53.215Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}