Playground
Api

Core Functions

The main functions for converting Zod schemas to Mongoose.

Core Functions

These functions form the core of the @nullix/zod-mongoose library, allowing you to convert Zod definitions into Mongoose-compatible schemas and definitions.

toMongooseSchema(zodSchema, options?)

Converts a Zod schema to a Mongoose schema instance (new mongoose.Schema(...)).

  • zodSchema: A Zod object or any Zod type.
  • options: Optional Mongoose SchemaOptions.
import { z } from 'zod/v4';
import { toMongooseSchema } from '@nullix/zod-mongoose';

const zodSchema = z.object({
  name: z.string(),
});

// Basic conversion with timestamps enabled
const mongooseSchema = toMongooseSchema(zodSchema, { timestamps: true });

Note: This function replaces the deprecated toZodMongooseSchema(). It now returns a full mongoose.Schema instance directly.

extractMongooseDef(zodSchema)

Converts a Zod schema to a Mongoose schema definition object (the POJO used as the first argument for new mongoose.Schema(...)). This is useful if you want to manually create the Mongoose schema, combine it with other definitions, or use it with Mongoose's .add() method.

import { z } from 'zod/v4';
import { extractMongooseDef } from '@nullix/zod-mongoose';

const zodSchema = z.object({
  name: z.string(),
});

const definition = extractMongooseDef(zodSchema);
// Result: { name: { type: String, required: true } }

withMongoose(zodSchema, metadata)

Attaches Mongoose-specific metadata to any Zod schema. MongooseMeta extends Mongoose's SchemaTypeOptions<any> and SchemaOptions, allowing you to specify both field-level options and top-level schema options.

  • metadata: A MongooseMeta object.

Field-level metadata

import { z } from 'zod/v4';
import { withMongoose } from '@nullix/zod-mongoose';

const zodSchema = z.object({
  username: withMongoose(z.string(), { 
    unique: true, 
    index: true,
    lowercase: true 
  }),
});

Schema-level metadata

You can also apply schema-level options (like disabling _id or setting a collection name) by wrapping the top-level Zod object.

const LogSchema = withMongoose(
  z.object({ message: z.string() }),
  { _id: false, id: false, collection: 'system_logs' }
);

Note: To define a custom Mongoose type, use withMongoose(zodSchema, { type: 'YourType' }) instead of the deprecated mongooseZodCustomType().