Skip to content

mongoose-guard

Validate request bodies with the Mongoose schema you already have. Pick the fields each route accepts, and everything else gets rejected.

mongoose-guard is a small TypeScript library for Node.js. It checks an incoming request body against an existing Mongoose model before your route code runs. You tell it which fields a route accepts. It rejects unknown fields, fields the route doesn’t allow, wrong types and anything your Mongoose rules reject, and it tells the client exactly what was wrong.

import { guard } from "mongoose-guard/express";
app.post("/signup", guard(User, { allow: ["name", "email", "password"] }), signup);

Send { "name": "Amrit", "email": "amrit@example.com", "password": "correct-horse", "role": "admin" } to that route and it never reaches signup. The client gets a 400:

{
"errors": [{ "code": "forbidden_field", "path": "role", "message": "Field is not allowed" }]
}

One schema, not two

Your Mongoose schema stays the source of truth. You don’t copy its rules into Zod or Joi.

Stops mass assignment

Each route lists the fields it accepts. role, credits or isVerified can’t sneak in through a signup form.

Strict types

"25" is not a number. Mongoose would cast it quietly. mongoose-guard reports it.

Blocks injection keys

__proto__, $where, $gt and dotted keys are rejected anywhere in the body.

  • Not a replacement for Zod everywhere. It validates JSON bodies that map onto a Mongoose model. Query strings, headers, route params and request shapes with no model behind them need another tool. See When to use it.
  • Not authentication or authorization. It checks what was sent, not who sent it.
  • Not an edge-runtime library. Mongoose needs Node.js, so mongoose-guard does too.
Packagemongoose-guard on npm
LicenseMIT
RuntimeNode.js 20 or newer
Mongoose8 and 9
Express4 and 5
Other frameworksanything that gives you a standard Request (Next.js, Hono, Remix, React Router, SvelteKit)
Module formatsESM and CommonJS, with TypeScript types
Runtime dependenciesnone