Seamlessly integrate Zod with Mongoose for full TypeScript type safety. Define your schemas once with Zod and automatically generate Mongoose schemas.
Explore the Documentation »
Getting Started | API Reference | Online Playground
Roadmap: Available in markdown()
In modern TypeScript applications, you often find yourself defining the same schema twice: once for runtime validation (Zod) and once for your database (Mongoose). zod-mongoose eliminates this duplication by providing a single source of truth.
- Type Safety: Full TypeScript support with inference from your Zod schemas.
- Automatic Mapping: Zod validators like
.min(), .max(), and .regex() are directly converted to Mongoose options.
- Zod Validation: Checks stored values and refinements during Mongoose validation. Parse transformed input once before storage; add an output pipe for stored-value validation. See validation.
- Native Discriminators: Automatically maps
z.discriminatedUnion to native Mongoose discriminators. Top-level unions use modelName (or derive it from collection) to avoid globally registered model-name collisions.
- Advanced Types: Built-in support for
ObjectId, Decimal128, BigInt, and more.
- Isomorphic: Share schemas between frontend and backend with
setFrontendMode.
pnpm add @nullix/zod-mongoose zod/v4 mongoose
import { z } from 'zod/v4';
import { toMongooseSchema } from '@nullix/zod-mongoose';
import mongoose from 'mongoose';
// Define your Zod schema
const UserZodSchema = z.object({
username: z.string().min(3).max(30),
email: z.string().email(),
age: z.number().min(18).optional(),
role: z.enum(['user', 'admin']).default('user'),
});
// Convert to Mongoose Schema
const UserSchema = toMongooseSchema(UserZodSchema);
// Create your Model
export const UserModel = mongoose.model('User', UserSchema);
3. Usage with Type Inference
// Infer the TypeScript type from the Zod schema
// It automatically includes { _id: mongoose.Types.ObjectId }
type User = z.infer<typeof UserZodSchema>;
async function createUser(data: User) {
const user = await UserModel.create(data);
return user;
}
This repository is a monorepo managed with pnpm workspaces.
# Install dependencies
pnpm install
# Build all packages
pnpm run build
# Run tests
pnpm run test
# Start the playground/docs in development
pnpm run dev
Contributions are welcome! Please see CONTRIBUTING.md for our development process.
MIT © Harm-Nullix
If you find @nullix/zod-mongoose helpful, consider supporting its development:
- 🩵 Sponsor on GitHub
- ⭐ Star the repository on GitHub
- 💬 Share it with your developer community