Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
@zodyac/zod-mongoose
Advanced tools
A library that allows you to generate mongoose schemas from zod objects.
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.
npm i @zodyac/zod-mongoose
pnpm add @zodyac/zod-mongoose
yarn add @zodyac/zod-mongoose
bun add @zodyac/zod-mongoose
[!WARNING] If you were using
zId
,zUUID
,z.objectId()
,z.mongoUUID()
before, please replace those withzId()
andzUUID()
.
zId
is now zId(ref?)
zUUID
is now zUUID()
First, extend Zod with extendZod
, then create your zod schema:
import { z } from "zod";
import { extendZod } from "@zodyac/zod-mongoose";
extendZod(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.
Full support list can be found in SUPPORTED.md:
✅ 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)
To make sure nothing is missing, you can use Schema.obj
:
// schema is mongoose schema
console.log(schema.obj);
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,
}),
);
You can use zId(ref?: string)
and zUUID(ref?: string)
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({
// Just the ID
someId: zId(),
wearable: zUUID(),
// With reference
companyId: zId("Company"), // equivalent to zId().ref("Company")
facilityId: zId().ref("Facility"),
device: zUUID("Device"), // equivalent to zUUID().ref("Device")
badgeId: zUUID().ref("Badge"),
// `refPath` support
storeId: zId().refPath("store"),
store: z.string(),
proxyId: zUUID().refPath("proxy"),
proxy: z.string(),
});
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",
),
});
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(),
});
//
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
is converted to SchemaTypes.Mixed
. It's not recommended to use it,
but it's there if you need it.
ZodRecord
is converted to Map
type. It's not recommended to use it, but it's
there if you need it.
Feel free to open issues and pull requests! Here's a quick guide to get you started:
npm i
npm test
npm run lint
(fix with npm run lint:fix
)MIT
FAQs
A library that allows you to generate mongoose schemas from zod objects.
We found that @zodyac/zod-mongoose demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.