zod-mongoose-bridge
v1.0.0
Published
A lightweight utility to dynamically generate Mongoose schemas from Zod schemas to eliminate model duplication.
Maintainers
Readme
zod-mongoose-bridge
A simple, lightweight utility to automatically generate Mongoose Schema definitions from Zod validation schemas. This eliminates the duplicate effort of writing separate schemas for data validation (Zod) and database models (Mongoose).
Features
- 🚀 Dynamic Translation — translates Zod types (
ZodString,ZodNumber,ZodBoolean,ZodDate,ZodEnum,ZodArray,ZodObject) to their Mongoose equivalents. - 🔒 Validation Sync — converts Zod enums into Mongoose validation enums automatically.
- ⚙️ Required Sync — handles
.optional()and.nullable()constraints, mapping them to Mongooserequired: falsevsrequired: true. - 📦 Nested Object Support — recursively resolves nested objects and arrays of nested objects.
Installation
npm install zod-mongoose-bridgeNote: zod and mongoose are required as peer dependencies.
Usage
const mongoose = require('mongoose');
const { z } = require('zod');
const { convertZodToMongoose } = require('zod-mongoose-bridge');
// 1. Define your validation schema with Zod
const UserValidationSchema = z.object({
username: z.string(),
email: z.string(),
age: z.number().optional(),
role: z.enum(['admin', 'user', 'guest']),
tags: z.array(z.string()),
address: z.object({
city: z.string(),
zipCode: z.string().optional()
})
});
// 2. Generate Mongoose schema definition
const mongooseDefinition = convertZodToMongoose(UserValidationSchema);
// 3. Create your Mongoose Model
const UserSchema = new mongoose.Schema(mongooseDefinition, { timestamps: true });
const UserModel = mongoose.model('User', UserSchema);Generated Schema Mapping Reference
The conversion performs the following mappings:
| Zod Type | Mongoose Type | Required State |
|---|---|---|
| z.string() | String | required: true (default) |
| z.string().optional() | String | required: false |
| z.number() | Number | required: true |
| z.boolean() | Boolean | required: true |
| z.date() | Date | required: true |
| z.enum(['a', 'b']) | String with enum: ['a', 'b'] | required: true |
| z.array(z.string()) | [String] | required: false |
| z.object({...}) | Nested object schema {...} | Checked properties |
Options
convertZodToMongoose(zodSchema, options) accepts:
const definition = convertZodToMongoose(UserValidationSchema, {
defaultRequired: false // If false, fields will not be marked 'required: true' unless explicitly validated (default: true)
});License
MIT
