yikart/AiToEarn · warning · BadRequestException

Invalid ObjectId

Error message

Invalid ObjectId

What it means

ObjectIdPipe is a NestJS validation pipe for route parameters; it throws BadRequestException 'Invalid ObjectId' when mongoose's isValidObjectId rejects the value. It guarantees route params meant to be Mongo ObjectIds are actually 24-char hex strings before reaching the handler.

Source

Thrown at project/aitoearn-electron/server/src/common/decorators/param-object-id.decorator.ts:7

import { Param, PipeTransform, BadRequestException } from '@nestjs/common';
import { isValidObjectId } from 'mongoose';

export class ObjectIdPipe implements PipeTransform {
  transform(value: string) {
    if (!isValidObjectId(value)) {
      throw new BadRequestException('Invalid ObjectId');
    }
    return value;
  }
}

export function ParamObjectId(property: string = 'id') {
  return Param(property, new ObjectIdPipe());
}

View on GitHub (pinned to d3aa8bea5b)

Solutions

  1. Fix the client to send a real 24-char hex ObjectId from Mongo.
  2. Add a client-side pre-check validating id format before navigating/calling.
  3. Check where the id originates — often an unset variable interpolated into the URL.
  4. If the collection uses non-ObjectId ids, remove the pipe or use different validation.

Example fix

// before
fetch(`/api/records/${recordId}`);
// after
if (!/^[0-9a-fA-F]{24}$/.test(recordId)) return;
fetch(`/api/records/${recordId}`);
Defensive patterns

Strategy: validation

Validate before calling

const OBJECT_ID_RE = /^[0-9a-fA-F]{24}$/;
function assertObjectId(id, name = 'id') {
  if (typeof id !== 'string' || !OBJECT_ID_RE.test(id)) {
    throw new Error(`${name} 不是有效的 ObjectId: ${id}`);
  }
  return id;
}

Type guard

function isValidObjectId(id) {
  return typeof id === 'string' && /^[0-9a-fA-F]{24}$/.test(id);
}

Try / catch

try {
  await api.get(`/records/${id}`);
} catch (e) {
  if (e?.response?.status === 400 && e.message === 'Invalid ObjectId') {
    throw new Error(`传入的 id 无效: "${id}",请检查数据来源`);
  } else throw e;
}

Prevention

When it happens

Trigger: Any route using @ParamObjectId receiving an id that is undefined, empty, non-hex, wrong length, or stringified values like 'undefined' or 'null'.

Common situations: Client building URLs with unset variables (/api/users/undefined); ids from a different scheme (UUIDs, numeric ids); truncated ids after URL manipulation.

Related errors


AI-assisted analysis of yikart/AiToEarn@d3aa8bea5b (2026-08-31). Data as JSON: /api/errors/5cfba7e1bbaed658. Report an issue: GitHub.