v3.3.1
Playground
Getting Started

Start Here

Install zod-mongoose and validate your first Mongoose document from a Zod schema.

Start Here

Define a Zod schema once, convert it to a Mongoose schema, and use the result with a normal Mongoose model. This example runs without a database connection so you can check the setup first.

Install the packages

Use Node.js 24 or newer. Install zod and Mongoose for a backend application. The package supports Mongoose 9 and Zod 4; zod/v4 is the import path, not the package name to install.

pnpm add @nullix/zod-mongoose zod@^4 mongoose@^9

Mongoose is an optional peer dependency if you only define shared Zod schemas in the browser. You need it on the server to call toMongooseSchema().

Create and validate a model

first-model.ts
import mongoose from 'mongoose';
import {z} from 'zod/v4';
import {toMongooseSchema} from '@nullix/zod-mongoose';

const UserZodSchema = z.object({
  name: z.string().min(2),
  email: z.email(),
});

const UserModel = mongoose.model('User', toMongooseSchema(UserZodSchema));
const user = new UserModel({name: 'Ada', email: 'ada@example.com'});

await user.validate();
console.log(user._id); // Mongoose generated an ObjectId

toMongooseSchema() returns a Mongoose Schema, so you can use normal Mongoose models and queries. validate() checks the document in memory. Connect to MongoDB before calling database methods such as create() or find().

Save a document

Once MongoDB is running, add this after the model definition above. Set MONGODB_URI for your own database; the fallback uses a local MongoDB instance.

await mongoose.connect(process.env.MONGODB_URI ?? 'mongodb://127.0.0.1:27017/zod-mongoose-example');
try {
  const saved = await UserModel.create({name: 'Ada', email: 'ada@example.com'});
  console.log(saved._id);
} finally {
  await mongoose.disconnect();
}

Find your next answer

I want to…Read
Type a create request and a stored documentModel and input types
Remove an ID from an embedded objectNested object IDs
Add custom validationValidate documents
Reference another modelReferences and population
Look up a function or mappingAPI reference

The playground lets you inspect a conversion before adding it to your project.