Seamlessly integrate Zod with Mongoose for full TypeScript type safety. Define your schemas once with Zod and automatically generate Mongoose schemas.
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. - Full Zod Validation: Automatically runs
schema.parse()during Mongoose validation to support complex Zod features like.refine()and.transform(). - Native Discriminators: Automatically maps
z.discriminatedUnionto native Mongoose discriminators. Top-level unions usemodelName(or derive it fromcollection) 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 mongooseimport { 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);// 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;
}- @nullix/zod-mongoose: The core library for schema conversion and type safety.
- @nullix/zod-mongoose-studio: A Monaco-powered component to visualize transformations.
- Documentation Site: Built with Nuxt UI Pro and Nuxt Content.
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 devContributions are welcome! Please see CONTRIBUTING.md for our development process.
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