@zodyac/zod-mongoose
TypeScript icon, indicating that this package has built-in type declarations

1.1.2 • Public • Published

Zod to mongoose schema converter

npm version

A part of Zodyac toolbox.

This package provides a function to convert zod object to mongoose schema.

Installation

npm i @zodyac/zod-mongoose

Usage

First, create your zod schema:

import { z } from 'zod';
import { zId, zUUID } from '@zodyac/zod-mongoose';

const zUser = z.object({
  name: z.string().min(3).max(255),
  age: z.number().min(18).max(100),
  active: z.boolean().default(false),
  access: z.enum(['admin', 'user']).default('user'),
  companyId: zId.describe('ObjectId:Company'),
  wearable: zUUID.describe('UUID:Wearable'),
  address: z.object({
    street: z.string(),
    city: z.string(),
    state: z.enum(['CA', 'NY', 'TX']),
  }),
  tags: z.array(z.string()),
  createdAt: z.date(),
  updatedAt: z.date(),
});

Then, convert it to mongoose schema and connect model:

import { zodSchema } from '@zodyac/zod-mongoose';
import { model } from 'mongoose';

const schema = zodSchema(zDoc);
const userModel = model('User', schema);

That's it! Now you can use your mongoose model as usual:

userModel.find({ name: 'John' });

Features

  • ✅ Basic types
  • ✅ Nested objects and schemas
  • ✅ Arrays
  • ✅ Enums (strings only)
  • ✅ Default values
  • ✅ Dates
  • ✅ ObjectId
  • ✅ ObjectId references
  • ✅ ZodAny as SchemaTypes.Mixed
  • 🔧 UUID (experimental)
  • 🔧 UUID references (experimental)
  • ❗️ Unions (not supported by mongoose)
  • ❗️ Intersection (not supported by mongoose)
  • ❗️ Indexes (not supported by zod)
  • ❗️ Number enums (comming soon)
  • ⏳ Regex validation (comming soon)
  • ⏳ Custom validators (comming soon)
  • ⏳ instanceOf (comming soon)
  • ⏳ Transform (comming soon)
  • ⏳ Refine (comming soon)

Checking schemas

To make sure nothing is missing, you can use Schema.obj:

// schema is mongoose schema
console.log(schema.obj);

Raw object

If you want to get raw object from zod schema to modify it, you can use zodSchemaRaw function:

import { zodSchemaRaw } from '@zodyac/zod-mongoose';
import { model, Schema } from 'mongoose';

const schema = zodSchemaRaw(zDoc);
schema.age.validate = (v: number) => v > 18;

const model = model('User', new Schema(schema));

License

MIT

Package Sidebar

Install

npm i @zodyac/zod-mongoose

Weekly Downloads

25

Version

1.1.2

License

MIT

Unpacked Size

44.1 kB

Total Files

8

Last publish

Collaborators

  • bebrasmell