Playground
Getting Started

Overview

An overview of zod-mongoose and how it helps integrate Zod with Mongoose.

Overview

@nullix/zod-mongoose is a comprehensive toolkit for integrating Zod with Mongoose. It allows you to use Zod as the single source of truth for your data models while leveraging the full power of Mongoose for database interaction.

Why zod-mongoose?

Declaring Mongoose schemas in a TypeScript environment has always been challenging in terms of type safety:

  • Manual Interfaces: You first declare a TypeScript interface for your document and then create a Mongoose schema matching that interface. This is error-prone as the two can easily fall out of sync.
  • InferSchemaType: Using mongoose.InferSchemaType<typeof schema> is limited; it doesn't support complex Zod features like narrowed types or native TypeScript enums, and has issues with fields named type.
  • Legacy Decorators: Tools like typegoose rely on older decorator proposals and often struggle with advanced type inference.

zod-mongoose solves these problems by allowing you to define your schemas in Zod and automatically converting them into fully-featured Mongoose schemas.

Key Features

  • Full Type Safety: Derive your document types directly from Zod schemas for perfect TypeScript integration.
  • Automatic Mapping: Zod's built-in validations (.min(), .max(), .regex(), etc.) are directly converted to Mongoose SchemaType options.
  • Native Discriminators: Automatically maps z.discriminatedUnion to native Mongoose discriminators for robust polymorphic data.
  • Advanced Types: Direct support for Mongoose-specific types like ObjectId and Buffer via specialized Zod helpers.
  • Isomorphic Support: Use the same schemas on the frontend and backend with setFrontendMode.
  • Nuxt 4 Ready: Built-in support for Nuxt 4 and Nitro environments, perfect for validating request bodies.
  • Hookable & Extensible: A rich hook system and support for Mongoose plugins allow you to customize the conversion process at any stage.

Automatic Validation Mapping

zod-mongoose automatically maps Zod's built-in validations and transformations to their corresponding Mongoose SchemaType options. For example:

  • .min(n) / .max(n) $\rightarrow$ minlength / maxlength (for strings)
  • .trim() $\rightarrow$ trim: true
  • .toLowerCase() $\rightarrow$ lowercase: true
  • .min(n) / .positive() $\rightarrow$ min: n (for numbers and dates)
  • .uuid() $\rightarrow$ type: Schema.Types.UUID
  • .datetime() / .date() $\rightarrow$ type: Date

For a full list of supported types and validations, see the Conversion Mapping.

Packages

The ecosystem consists of several packages: