### Install Zod to Mongoose Converter Source: https://github.com/git-zodyac/mongoose/blob/main/README.md Install the package using npm, pnpm, yarn, or bun. ```bash npm i @zodyac/zod-mongoose pnpm add @zodyac/zod-mongoose yarn add @zodyac/zod-mongoose bun add @zodyac/zod-mongoose ``` -------------------------------- ### Convert Zod Object to Mongoose Schema Source: https://context7.com/git-zodyac/mongoose/llms.txt Use `zodSchema` to convert a Zod object into a Mongoose schema. An optional `SchemaOptions` object can be provided for Mongoose schema configuration. This example demonstrates creating a User model with various field types and validations. ```typescript import { z } from "zod"; import { extendZod, zId, zUUID, zodSchema } from "@zodyac/zod-mongoose"; import { connect, model } from "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), role: z.enum(["admin", "user", "guest"]).default("user"), companyId: zId("Company"), // ObjectId referencing "Company" collection deviceId: zUUID("Device"), // UUID referencing "Device" collection email: z.string().unique().sparse(), phone: z.string().unique().refine( (v) => /^\d{10}$/.test(v), "Must be a 10-digit phone number" ), 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().optional(), }); // Convert to Mongoose Schema (with timestamps option) const userSchema = zodSchema(zUser, { timestamps: true }); // Inspect the generated schema definition console.log(userSchema.obj); // { // name: { type: String, required: true, minLength: 3, maxLength: 255, unique: false, sparse: false }, // age: { type: Number, required: true, min: 18, max: 100, unique: false, sparse: false }, // active: { type: Boolean, required: true, default: [Function] }, // role: { type: String, required: true, enum: ['admin','user','guest'], default: [Function] }, // companyId: { type: ObjectId, required: true, ref: 'Company' }, // ... // } await connect("mongodb://localhost:27017/mydb"); const User = model("User", userSchema); const user = await User.create({ name: "Alice", age: 30, role: "admin", companyId: "64f1a2b3c4d5e6f7a8b9c0d1", deviceId: "550e8400-e29b-41d4-a716-446655440000", email: "alice@example.com", phone: "5551234567", address: { street: "123 Main St", city: "San Francisco", state: "CA" }, tags: ["typescript", "mongodb"], createdAt: new Date(), }); ``` -------------------------------- ### Get Raw Mongoose Schema Object from Zod Source: https://github.com/git-zodyac/mongoose/blob/main/README.md Obtain the raw Mongoose schema object from a Zod schema using `zodSchemaRaw` to allow for direct modification before creating the Mongoose Schema. ```typescript 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, }), ); ``` -------------------------------- ### Get Raw Mongoose Schema Definition with zodSchemaRaw Source: https://context7.com/git-zodyac/mongoose/llms.txt Use `zodSchemaRaw` to obtain the raw Mongoose schema definition object. This allows for manual modification of field definitions, such as adding indexes, before constructing the `mongoose.Schema` instance. ```typescript import { z } from "zod"; import { extendZod, zodSchemaRaw } from "@zodyac/zod-mongoose"; import { model, Schema } from "mongoose"; extendZod(z); const zProduct = z.object({ sku: z.string().unique(), name: z.string().min(1).max(500), price: z.number().min(0), stock: z.number().min(0).default(0), }); // Get the raw definition object const rawSchema = zodSchemaRaw(zProduct); // Manually add a compound index or other Mongoose-specific options rawSchema.sku.index = true; rawSchema.name.text = true; // enable full-text search index // Construct the Schema with additional Mongoose options const productSchema = new Schema(rawSchema, { timestamps: true }); productSchema.index({ name: "text" }); const Product = model("Product", productSchema); ``` -------------------------------- ### Convert Zod Union to Mongoose String Type Source: https://github.com/git-zodyac/mongoose/blob/main/README.md Zod union types are converted to their inner type by default. This example shows a Zod union of string and number becoming a Mongoose string type. ```typescript const zUser = z.object({ access: z.union([z.string(), z.number()]), }); // Will become // { // access: { // type: String, // }, // } ``` -------------------------------- ### zodSchema(schema, options?) Source: https://context7.com/git-zodyac/mongoose/llms.txt Converts a ZodObject into a mongoose.Schema instance. It accepts an optional SchemaOptions object, such as `{ timestamps: true }`, which is passed directly to the Mongoose Schema constructor. ```APIDOC ## zodSchema(schema, options?) ### Description Converts a `ZodObject` into a `mongoose.Schema` instance. Accepts an optional `SchemaOptions` object (e.g. `{ timestamps: true }`) passed directly to the Mongoose `Schema` constructor. ### Method Function Call ### Parameters - **schema** (ZodObject): The Zod object schema to convert. - **options** (SchemaOptions, optional): Options to pass to the Mongoose Schema constructor. ### Usage Example ```typescript import { z } from "zod"; import { extendZod, zId, zUUID, zodSchema } from "@zodyac/zod-mongoose"; import { connect, model } from "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), role: z.enum(["admin", "user", "guest"]) .default("user"), companyId: zId("Company"), // ObjectId referencing "Company" collection deviceId: zUUID("Device"), // UUID referencing "Device" collection email: z.string().unique().sparse(), phone: z.string().unique().refine( (v) => /^\d{10}$/.test(v), "Must be a 10-digit phone number" ), 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().optional(), }); // Convert to Mongoose Schema (with timestamps option) const userSchema = zodSchema(zUser, { timestamps: true }); // Inspect the generated schema definition console.log(userSchema.obj); await connect("mongodb://localhost:27017/mydb"); const User = model("User", userSchema); const user = await User.create({ name: "Alice", age: 30, role: "admin", companyId: "64f1a2b3c4d5e6f7a8b9c0d1", deviceId: "550e8400-e29b-41d4-a716-446655440000", email: "alice@example.com", phone: "5551234567", address: { street: "123 Main St", city: "San Francisco", state: "CA" }, tags: ["typescript", "mongodb"], createdAt: new Date(), }); ``` ``` -------------------------------- ### Use Mongoose Model Source: https://github.com/git-zodyac/mongoose/blob/main/README.md After creating the Mongoose model, it can be used for standard database operations like finding documents. ```typescript userModel.find({ name: "John" }); ``` -------------------------------- ### .unique() and .sparse() - Extended Zod Methods Source: https://context7.com/git-zodyac/mongoose/llms.txt After calling `extendZod(z)`, Zod's `ZodString`, `ZodNumber`, and `ZodDate` types gain `.unique(bool?)` and `.sparse(bool?)` methods. These methods allow you to specify unique and sparse index modifiers directly within your Zod schemas for Mongoose. ```APIDOC ## .unique() and .sparse() — Extended Zod Methods ### Description After calling `extendZod(z)`, `ZodString`, `ZodNumber`, and `ZodDate` gain `.unique(bool?)` and `.sparse(bool?)` methods that mark fields with the corresponding Mongoose index modifiers. ### Usage ```typescript import { z } from "zod"; import { extendZod, zodSchema } from "@zodyac/zod-mongoose"; extendZod(z); const zUserProfile = z.object({ // Unique index on string username: z.string().unique(), // Unique + sparse (allows multiple null/undefined values in the index) email: z.string().unique().sparse(), // Sparse-only (indexed but not unique) nickname: z.string().sparse(), // Unique number field employeeId: z.number().unique(), // Unique + sparse date deletedAt: z.date().unique().sparse(), }); const schema = zodSchema(zUserProfile); console.log((schema.obj.username as any).unique); // true console.log((schema.obj.email as any).sparse); // true console.log((schema.obj.employeeId as any).unique); // true console.log((schema.obj.deletedAt as any).sparse); // true ``` ``` -------------------------------- ### zId(ref?) Source: https://context7.com/git-zodyac/mongoose/llms.txt Creates a Zod type that represents a MongoDB `ObjectId`. It supports an optional `ref` string for Mongoose population and can be chained with methods like `.ref()`, `.refPath()`, `.unique()`, `.sparse()`, and `.optional()` for advanced configurations. ```APIDOC ## zId(ref?) ### Description Creates a Zod type representing a MongoDB `ObjectId` field. Accepts an optional `ref` string for Mongoose population. Supports chaining `.ref()`, `.refPath()`, `.unique()`, `.sparse()`, and `.optional()`. ### Usage ```typescript import { z } from "zod"; import { extendZod, zId, zodSchema } from "@zodyac/zod-mongoose"; import { Types } from "mongoose"; extendZod(z); const zComment = z.object({ // Required ObjectId with static ref postId: zId("Post"), // ObjectId with chained .ref() authorId: zId().ref("User"), // Dynamic ref resolved from another field targetId: zId().refPath("targetModel"), targetModel: z.enum(["Post", "Video"]), // Optional ObjectId (no ref) parentId: zId().optional(), // Unique + sparse ObjectId externalRef: zId().unique().sparse(), }); const commentSchema = zodSchema(zComment); // Runtime validation — zId accepts both string and ObjectId instances const parsed = zId("Post").safeParse(new Types.ObjectId()); // { success: true, data: ObjectId(...) } const parsedStr = zId("Post").safeParse("64f1a2b3c4d5e6f7a8b9c0d1"); // { success: true, data: "64f1a2b3c4d5e6f7a8b9c0d1" } const invalid = zId("Post").safeParse("not-an-id"); // { success: false, error: ZodError [{ message: "Invalid ObjectId" }] } ``` ``` -------------------------------- ### Convert Zod Schema to Mongoose Schema and Model Source: https://github.com/git-zodyac/mongoose/blob/main/README.md Convert the defined Zod schema to a Mongoose schema using zodSchema and then create a Mongoose model. ```typescript import { zodSchema } from "@zodyac/zod-mongoose"; import { model } from "mongoose"; const schema = zodSchema(zDoc); const userModel = model("User", schema); ``` -------------------------------- ### Extend Zod with Mongoose Methods Source: https://context7.com/git-zodyac/mongoose/llms.txt Call `extendZod` once at application startup to enable Mongoose-specific methods like `.unique()` and `.sparse()` on Zod types. This function is idempotent. ```typescript import { z } from "zod"; import { extendZod } from "@zodyac/zod-mongoose"; // Call once at application startup (safe to call multiple times - idempotent) extendZod(z); // After extending, .unique() and .sparse() are available on string/number/date const zEmail = z.string().unique().sparse(); const zScore = z.number().unique(); const zTimestamp = z.date().unique().sparse(); ``` -------------------------------- ### Define ObjectID and UUID Fields with References Source: https://github.com/git-zodyac/mongoose/blob/main/README.md Use `zId()` and `zUUID()` to define fields as ObjectID and UUID, optionally specifying a reference to another collection using `.ref()` or `refPath`. ```typescript 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(), }); ``` -------------------------------- ### Use z.any() for SchemaTypes.Mixed in Mongoose Source: https://context7.com/git-zodyac/mongoose/llms.txt Map `z.any()` fields to Mongoose's `SchemaTypes.Mixed` to allow storing arbitrary data types. This is useful for flexible payload fields. ```typescript import { z } from "zod"; import { extendZod, zodSchema } from "@zodyac/zod-mongoose"; import { SchemaTypes } from "mongoose"; extendZod(z); const zEvent = z.object({ name: z.string(), payload: z.any(), // → SchemaTypes.Mixed }); const schema = zodSchema(zEvent); console.log((schema.obj.payload as any).type === SchemaTypes.Mixed); // true ``` -------------------------------- ### Extend Zod and Define User Schema Source: https://github.com/git-zodyac/mongoose/blob/main/README.md Extend Zod with extendZod and define a user schema using Zod object, including various types like string, number, boolean, enum, object, array, date, ObjectId, and UUID. ```typescript 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(), }); ``` -------------------------------- ### extendZod(z) Source: https://context7.com/git-zodyac/mongoose/llms.txt Extends the Zod library instance with Mongoose-specific methods like .unique() and .sparse() on ZodString, ZodNumber, and ZodDate. This function must be called once before using other features of the library. It is idempotent, so it's safe to call multiple times. ```APIDOC ## extendZod(z) ### Description Extends the Zod library instance with Mongoose-specific methods (`unique`, `sparse`) on `ZodString`, `ZodNumber`, and `ZodDate`, and wires up refinement metadata forwarding. **Must be called once** before using any other feature of the library. ### Method Function Call ### Parameters - **z** (Zod): The Zod library instance to extend. ### Usage Example ```typescript import { z } from "zod"; import { extendZod } from "@zodyac/zod-mongoose"; // Call once at application startup (safe to call multiple times - idempotent) extendZod(z); // After extending, .unique() and .sparse() are available on string/number/date const zEmail = z.string().unique().sparse(); const zScore = z.number().unique(); const zTimestamp = z.date().unique().sparse(); ``` ``` -------------------------------- ### Nested Subdocuments and Arrays of Objects Source: https://context7.com/git-zodyac/mongoose/llms.txt Nested Zod objects become Mongoose subdocuments, and arrays of Zod objects become arrays of subdocuments. Optional nested objects are marked as not required. ```typescript import { z } from "zod"; import { extendZod, zodSchema } from "@zodyac/zod-mongoose"; extendZod(z); const zComment = z.object({ body: z.string().min(1), createdAt: z.date(), edited: z.boolean().default(false), }); const zPost = z.object({ title: z.string().min(3).max(200), body: z.string(), // Required nested subdocument metadata: z.object({ slug: z.string().unique(), wordCount: z.number().min(0), published: z.boolean().default(false), }), // Optional nested subdocument seo: z.object({ metaTitle: z.string().optional(), metaDescription: z.string().optional(), }).optional(), // Array of subdocuments comments: z.array(zComment), tags: z.array(z.string()), }); const postSchema = zodSchema(zPost); // Required nested object is inlined directly // (schema.obj.metadata.slug.type === String) // Optional nested object is wrapped with { type: {...}, required: false } // (schema.obj.seo.required === false) // Array of objects becomes [{ body: {...}, createdAt: {...}, edited: {...} }] // (Array.isArray(schema.obj.comments.type) === true) ``` -------------------------------- ### zodSchemaRaw(schema) Source: https://context7.com/git-zodyac/mongoose/llms.txt Retrieves the raw Mongoose schema definition object from a Zod schema. This allows for manual modification of field definitions, such as adding indexes or other Mongoose-specific options, before constructing the final Mongoose Schema. ```APIDOC ## zodSchemaRaw(schema) ### Description Returns the raw Mongoose schema definition object instead of a `mongoose.Schema` instance. Use this when you need to manually modify field definitions before constructing the schema (e.g., adding indexes not supported by Zod). ### Usage ```typescript import { z } from "zod"; import { extendZod, zodSchemaRaw } from "@zodyac/zod-mongoose"; import { model, Schema } from "mongoose"; extendZod(z); const zProduct = z.object({ sku: z.string().unique(), name: z.string().min(1).max(500), price: z.number().min(0), stock: z.number().min(0).default(0), }); // Get the raw definition object const rawSchema = zodSchemaRaw(zProduct); // Manually add a compound index or other Mongoose-specific options rawSchema.sku.index = true; rawSchema.name.text = true; // enable full-text search index // Construct the Schema with additional Mongoose options const productSchema = new Schema(rawSchema, { timestamps: true }); productSchema.index({ name: "text" }); const Product = model("Product", productSchema); ``` ``` -------------------------------- ### Apply Unique and Sparse Index Modifiers Source: https://context7.com/git-zodyac/mongoose/llms.txt After calling `extendZod(z)`, `ZodString`, `ZodNumber`, and `ZodDate` gain `.unique(bool?)` and `.sparse(bool?)` methods. These mark fields for corresponding Mongoose index modifiers. ```typescript import { z } from "zod"; import { extendZod, zodSchema } from "@zodyac/zod-mongoose"; extendZod(z); const zUserProfile = z.object({ // Unique index on string username: z.string().unique(), // Unique + sparse (allows multiple null/undefined values in the index) email: z.string().unique().sparse(), // Sparse-only (indexed but not unique) nickname: z.string().sparse(), // Unique number field employeeId: z.number().unique(), // Unique + sparse date deletedAt: z.date().unique().sparse(), }); const schema = zodSchema(zUserProfile); console.log((schema.obj.username as any).unique); // true console.log((schema.obj.email as any).sparse); // true console.log((schema.obj.employeeId as any).unique); // true console.log((schema.obj.deletedAt as any).sparse); // true ``` -------------------------------- ### Make Fields Sparse Source: https://github.com/git-zodyac/mongoose/blob/main/README.md Apply the `.sparse()` method to String, Number, or Date fields to allow for null or undefined values while still enforcing uniqueness if `.unique()` is also applied. ```typescript import { z } from "zod"; import { extendZod, zodSchema } from "@zodyac/zod-mongoose"; extendZod(z); const zUser = z.object({ email: z.string().sparse(), // with unique // email: z.string()..unique().sparse(), }); // ``` -------------------------------- ### zUUID(ref?) Source: https://context7.com/git-zodyac/mongoose/llms.txt Creates a Zod type for MongoDB `UUID` fields. It mirrors the `zId` API, offering chainable methods like `.ref()`, `.refPath()`, `.unique()`, `.sparse()`, and `.optional()`, and maps to Mongoose's `SchemaTypes.UUID`. ```APIDOC ## zUUID(ref?) ### Description Creates a Zod type representing a MongoDB `UUID` field. Mirrors the `zId` API with the same chainable methods (`.ref()`, `.refPath()`, `.unique()`, `.sparse()`, `.optional()`), but maps to `SchemaTypes.UUID` in Mongoose. ### Usage ```typescript import { z } from "zod"; import { extendZod, zUUID, zodSchema } from "@zodyac/zod-mongoose"; import { Types } from "mongoose"; extendZod(z); const zDevice = z.object({ // UUID with static collection ref deviceId: zUUID("Device"), // UUID with chained .ref() ownerId: zUUID().ref("User"), // Dynamic ref path linkedId: zUUID().refPath("linkedModel"), linkedModel: z.string(), // Unique + sparse UUID serialNumber: zUUID().unique().sparse(), // Optional UUID pairedWith: zUUID().optional(), }); const deviceSchema = zodSchema(zDevice); // Runtime validation const parsed = zUUID().safeParse(new Types.UUID()); // { success: true } const parsedStr = zUUID().safeParse("550e8400-e29b-41d4-a716-446655440000"); // { success: true } const invalid = zUUID().safeParse("not-a-uuid"); // { success: false, error: ZodError [{ message: "Invalid UUID" }] } ``` ``` -------------------------------- ### Apply Zod Refinements for Validation Source: https://github.com/git-zodyac/mongoose/blob/main/README.md Utilize Zod's `.refine()` method to add custom validation logic to fields within the schema, such as validating a phone number format. ```typescript 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", ), }); ``` -------------------------------- ### Maps and Records Conversion Source: https://context7.com/git-zodyac/mongoose/llms.txt Zod's `z.map()` and `z.record()` are converted to Mongoose `Map` types. The value schema determines the type of the map's `of` field. ```typescript import { z } from "zod"; import { extendZod, zId, zUUID, zodSchema } from "@zodyac/zod-mongoose"; extendZod(z); const zAnalytics = z.object({ // Map with object values clicksByPage: z.map(z.string(), z.object({ count: z.number() })), // Record (also becomes Map) sessionsByUser: z.record(z.string(), z.date()), // Map keyed by UUID deviceLastSeen: z.record(zUUID(), z.date()), // Map keyed by ObjectId userScores: z.record(zId(), z.number()), }); const schema = zodSchema(zAnalytics); console.log((schema.obj.clicksByPage as any).type); // Map console.log((schema.obj.clicksByPage as any).of.count.type); // Number console.log((schema.obj.sessionsByUser as any).of.type); // Date console.log((schema.obj.deviceLastSeen as any).of.type); // Date ``` -------------------------------- ### Define Nullable and Optional Fields in Mongoose Schema Source: https://context7.com/git-zodyac/mongoose/llms.txt Use `z.optional()` for fields that are not required and `z.nullable()` for fields that can be null. This directly translates to Mongoose schema properties like `required: false` and default values. ```typescript import { z } from "zod"; import { extendZod, zId, zodSchema } from "@zodyac/zod-mongoose"; extendZod(z); const zProfile = z.object({ bio: z.string().optional(), // required: false deletedAt: z.date().optional(), // required: false parentId: zId().optional(), // required: false, type: ObjectId middleName: z.string().nullable(), // required: false, default: null }); const schema = zodSchema(zProfile); console.log((schema.obj.bio as any).required); // false console.log((schema.obj.deletedAt as any).required); // false console.log((schema.obj.parentId as any).required); // false console.log((schema.obj.middleName as any).default()); // null ``` -------------------------------- ### Validation via Zod Refinements Source: https://context7.com/git-zodyac/mongoose/llms.txt Use Zod's `.refine()` method to define custom validation logic and error messages that are automatically translated to Mongoose's `validate` field option. ```typescript import { z } from "zod"; import { extendZod, zodSchema } from "@zodyac/zod-mongoose"; extendZod(z); const zOrder = z.object({ phone: z.string().refine( (v) => /^\d{3}-\d{3}-\d{4}$\.test(v), "Phone must match format 000-000-0000" ), amount: z.number().refine( (v) => v > 0, "Amount must be positive" ), hash: z.string() .refine((val) => val.startsWith("sha256:"), { message: "Invalid hash prefix" }) .array(), }); const orderSchema = zodSchema(zOrder); // Mongoose will use these validators at document save time: // orderSchema.obj.phone.validate.validator("123-456-7890") => true // orderSchema.obj.phone.validate.message => "Phone must match format 000-000-0000" // orderSchema.obj.amount.validate.validator(0) => false ``` -------------------------------- ### Inspect Mongoose Schema Object Source: https://github.com/git-zodyac/mongoose/blob/main/README.md Access the underlying Mongoose schema object using `schema.obj` for inspection or debugging. ```typescript // schema is mongoose schema console.log(schema.obj); ``` -------------------------------- ### Create MongoDB ObjectId Type with zId Source: https://context7.com/git-zodyac/mongoose/llms.txt The `zId` function creates a Zod type for MongoDB `ObjectId`. It supports optional `ref` for Mongoose population and chainable methods like `.ref()`, `.refPath()`, `.unique()`, `.sparse()`, and `.optional()`. ```typescript import { z } from "zod"; import { extendZod, zId, zodSchema } from "@zodyac/zod-mongoose"; import { Types } from "mongoose"; extendZod(z); const zComment = z.object({ // Required ObjectId with static ref postId: zId("Post"), // ObjectId with chained .ref() authorId: zId().ref("User"), // Dynamic ref resolved from another field targetId: zId().refPath("targetModel"), targetModel: z.enum(["Post", "Video"]), // Optional ObjectId (no ref) parentId: zId().optional(), // Unique + sparse ObjectId externalRef: zId().unique().sparse(), }); const commentSchema = zodSchema(zComment); // Runtime validation — zId accepts both string and ObjectId instances const parsed = zId("Post").safeParse(new Types.ObjectId()); // { success: true, data: ObjectId(...) } const parsedStr = zId("Post").safeParse("64f1a2b3c4d5e6f7a8b9c0d1"); // { success: true, data: "64f1a2b3c4d5e6f7a8b9c0d1" } const invalid = zId("Post").safeParse("not-an-id"); // { success: false, error: ZodError [{ message: "Invalid ObjectId" }] } ``` -------------------------------- ### Default Values Forwarding Source: https://context7.com/git-zodyac/mongoose/llms.txt Zod's `.default()` values are preserved and exposed as getter functions on the Mongoose schema, allowing Mongoose to use them for default field values. ```typescript import { z } from "zod"; import { extendZod, zodSchema } from "@zodyac/zod-mongoose"; extendZod(z); enum Role { Admin = "admin", User = "user" } const zMember = z.object({ active: z.boolean().default(false), role: z.enum(["admin", "user"]).default("user"), nativeRole: z.nativeEnum(Role).default(Role.User), score: z.number().default(0), tags: z.array(z.string()).default(["general"]), }); const schema = zodSchema(zMember); // Default values are exposed as getter functions console.log((schema.obj.active as any).default()); // false console.log((schema.obj.role as any).default()); // "user" console.log((schema.obj.nativeRole as any).default()); // "user" console.log((schema.obj.score as any).default()); // 0 console.log((schema.obj.tags as any).default()); // ["general"] ``` -------------------------------- ### Make Fields Unique Source: https://github.com/git-zodyac/mongoose/blob/main/README.md Add a unique constraint to String, Number, or Date fields by calling the `.unique()` method on the Zod schema definition. ```typescript import { z } from "zod"; import { extendZod, zodSchema } from "@zodyac/zod-mongoose"; extendZod(z); const zUser = z.object({ phone: z.string().unique(), }); // ``` -------------------------------- ### Create MongoDB UUID Type with zUUID Source: https://context7.com/git-zodyac/mongoose/llms.txt The `zUUID` function creates a Zod type for MongoDB `UUID`. It mirrors the `zId` API with chainable methods and maps to `SchemaTypes.UUID` in Mongoose. ```typescript import { z } from "zod"; import { extendZod, zUUID, zodSchema } from "@zodyac/zod-mongoose"; import { Types } from "mongoose"; extendZod(z); const zDevice = z.object({ // UUID with static collection ref deviceId: zUUID("Device"), // UUID with chained .ref() ownerId: zUUID().ref("User"), // Dynamic ref path linkedId: zUUID().refPath("linkedModel"), linkedModel: z.string(), // Unique + sparse UUID serialNumber: zUUID().unique().sparse(), // Optional UUID pairedWith: zUUID().optional(), }); const deviceSchema = zodSchema(zDevice); // Runtime validation const parsed = zUUID().safeParse(new Types.UUID()); // { success: true } const parsedStr = zUUID().safeParse("550e8400-e29b-41d4-a716-446655440000"); // { success: true } const invalid = zUUID().safeParse("not-a-uuid"); // { success: false, error: ZodError [{ message: "Invalid UUID" }] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.