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
- Fix the client to send a real 24-char hex ObjectId from Mongo.
- Add a client-side pre-check validating id format before navigating/calling.
- Check where the id originates — often an unset variable interpolated into the URL.
- 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
- Guard URL template strings — /x/${id} with undefined becomes '/x/undefined'.
- Validate ids at the client boundary before navigation/API calls.
- UUIDs and numeric ids will fail this pipe — only Mongo ObjectIds pass.
- Return 24-hex ids from list endpoints so round-trips stay valid.
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
- userId, accountId和file是必须的
- tweetId, userId和accountId是必须的
- userId, accountId和query是必须的
- tweetId, rating和accountId是必须的
- 参数错误: rating必须为like或unlike
AI-assisted analysis of yikart/AiToEarn@d3aa8bea5b (2026-08-31).
Data as JSON: /api/errors/5cfba7e1bbaed658.
Report an issue: GitHub.