Start Here
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
npm install @nullix/zod-mongoose zod@^4 mongoose@^9
yarn add @nullix/zod-mongoose zod@^4 mongoose@^9
bun 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
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 document | Model and input types |
| Remove an ID from an embedded object | Nested object IDs |
| Add custom validation | Validate documents |
| Reference another model | References and population |
| Look up a function or mapping | API reference |
The playground lets you inspect a conversion before adding it to your project.