Validate ObjectId Middleware
The Validate ObjectId Middleware ensures that route parameters intended to be MongoDB ObjectIds are valid before the request reaches your controller. This prevents CastError exceptions from Mongoose and ensures strictly typed ID handling.
It is designed to be:
- Robust: Checks for valid 24-character hex strings using Mongoose's
isValidObjectId. - Flexible: Can validate any route parameter name (defaults to
id). - Clean: Throws a standardized
ApiErrorif validation fails.
Installation Guide
Install the component using the Servercn CLI:
npx servercn-cli add validate-objectidBasic Implementation
MVC: src/middlewares/validate-id.ts
Feature: src/shared/middlewares/validate-id.ts
Usage Example
Apply the middleware to any route that contains an :id parameter.
Why Use This?
Without this middleware, passing an invalid ID (e.g., 123) to a Mongoose query like findById causes a CastError, which might crash your app or result in a generic 500 Internal Server Error if not handled properly. This middleware catches the issue early and returns a proper 400 Bad Request.