npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zodyac/zod-mongoose

v3.0.0

Published

A library that allows you to generate mongoose schemas from zod objects.

Downloads

1,870

Readme

Zod to Mongoose schema converter

NPM Version NPM Downloads npm bundle size Test coverage

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

[!NOTE] This package is in early development stage. Please report any issues you find and please expect API to change in minor versions.

Installation

npm i @zodyac/zod-mongoose

pnpm add @zodyac/zod-mongoose

yarn add @zodyac/zod-mongoose

bun add @zodyac/zod-mongoose

Breaking changes

[!WARNING] If you were using zId, zUUID, z.objectId(), z.mongoUUID() before, please replace those with zId() and zUUID().

  • zId is now zId(ref?)
  • zUUID is now zUUID()

Usage

First, extend Zod with extendZod, then create your zod schema:

import { z } from "zod";
import { extendZod } from "@zodyac/zod-mongoose";

extend(z);

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("Company"),
  wearable: zUUID(),
  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" });

[Note] extendZod should be called once for the whole application.

Features

  • ✅ Basic types

  • ✅ Nested objects and schemas

  • ✅ Arrays

  • ✅ Enums (strings only)

  • ✅ Default values

  • ✅ Maps

  • ✅ Dates

  • ✅ ObjectId

  • ✅ ObjectId references

  • ✅ ZodAny as SchemaTypes.Mixed

  • ✅ Validation using refinement for String, Number, Date

  • ✅ Unique for String, Number, Date, ObjectId and UUID

  • ⚠️ Record (Being converted to Map)

  • ⚠️ Unions (Not supported by mongoose, will pick first inner type)

  • ❗️ Intersection (not supported by mongoose)

  • ❗️ Set (not supported by mongoose)

  • ❗️ Indexes (not supported by zod)

  • ⏳ Regex validation (coming soon)

  • ⏳ instanceOf (coming 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 { extendZod, zodSchemaRaw } from "@zodyac/zod-mongoose";
import { model, Schema } from "mongoose";

extendZod(z);

const schema = zodSchemaRaw(zDoc);
schema.age.index = true

const model = model("User", new Schema(schema, {
  timestamps: true,
}));

ObjectID and UUID

You can use zId(ref?: string) and zUUID() to describe fields as ObjectID and UUID and add reference to another collection:

import { extendZod } from "@zodyac/zod-mongoose";
import { z } from "zod"

extendZod(z);

const zUser = z.object({
  someId: zId(),
  companyId: zId("Company"),
  facilityId: zId().ref("Facility"),
  wearable: zUUID(),
});

Validation

You can use zod refinement to validate your mongoose models:

import { z } from "zod";
import { extendZod, zodSchema } from "@zodyac/zod-mongoose";

extendZod(z);

const zUser = z.object({
  phone: z.string().refine((v) => v.match(/^\d{3}-\d{3}-\d{4}$/), "Invalid phone number"),
});

Unique fields

To make a String, Number or Date unique, call .unique():

import { z } from "zod";
import { extendZod, zodSchema } from "@zodyac/zod-mongoose";

extendZod(z);

const zUser = z.object({
  phone: z.string().unique(),
});

//

Warnings

ZodUnion types

Union types are not supported by mongoose. If you have a union type in your zod schema, it will be converted to it's inner type by default.

const zUser = z.object({
  access: z.union([z.string(), z.number()]),
});

// Will become
// {
//   access: {
//     type: String,
//   },
// }

ZodAny

ZodAny is converted to SchemaTypes.Mixed. It's not recommended to use it, but it's there if you need it.

ZodRecord

ZodRecord is converted to Map type. It's not recommended to use it, but it's there if you need it.

Contributing

Feel free to open issues and pull requests! Here's a quick guide to get you started:

  • Fork the repository
  • Install linter and formatter for VSCode: Biome
  • Install dependencies: npm i
  • Make changes
  • Run tests: npm test
  • Run linter: npm run lint (fix with npm run lint:fix)
  • Commit and push your changes
  • Open a pull request

License

MIT