v3.6.0
Playground
Guides

Validate Documents

Run Zod refinements during Mongoose validation and understand when transforms affect stored values.

Validate Documents

toMongooseSchema() maps supported Zod checks to Mongoose options. Its default post('validate') hook checks stored values against Zod, so refinements that Mongoose cannot represent still reject invalid documents.

Add a refinement

booking.ts
import mongoose from 'mongoose';
import {z} from 'zod/v4';
import {toMongooseSchema} from '@nullix/zod-mongoose';

const BookingZodSchema = z.object({
  startsAt: z.date(),
  endsAt: z.date(),
}).refine(({startsAt, endsAt}) => endsAt > startsAt, {
  message: 'End must be after start',
  path: ['endsAt'],
});

const Booking = mongoose.model('Booking', toMongooseSchema(BookingZodSchema));
const booking = new Booking({
  startsAt: new Date('2026-01-02'),
  endsAt: new Date('2026-01-01'),
});

await booking.validate(); // Rejects the document; no database connection is needed.

The hook validates stored values after Mongoose casting. Ordinary field rules and object refinements still run. Query updates such as updateOne() do not run this document hook; see Object Modes and Unknown Keys.

Parse transformed input once

Parse input before constructing or assigning a document. Add an output pipe when you want Mongoose to know the stored type and validate it on later saves:

transformed-input.ts
import mongoose from 'mongoose';
import {z} from 'zod/v4';
import {toMongooseSchema} from '@nullix/zod-mongoose';

const Amount = z.string().transform(Number).pipe(z.number().positive());
const InvoiceInput = z.object({amount: Amount});
const Invoice = mongoose.model('Invoice', toMongooseSchema(InvoiceInput));

const invoice = new Invoice(InvoiceInput.parse({amount: '42'}));
await invoice.validate(); // amount is 42; the string transform is not rerun.

invoice.amount = Amount.parse('56');
await invoice.validate(); // amount is 56.
invoice.amount = -1;
await invoice.validate(); // Rejects: the output must be positive.

Document validation checks the output side of pipes, codecs, and preprocessors. It does not rerun their input callbacks or assign parsed results back to the document. Repeated validation and loading a saved document therefore do not transform values again. Use parseAsync() at the input boundary for async transforms.

A bare .transform() has no runtime output schema. Such fields use Mongoose Mixed, preserve the value you supply, and skip input-side rules during document validation. TypeScript still infers the return type, but cannot make it available at runtime. Add .pipe(outputSchema) to validate stored output. A withMongoose(..., {type: Number}) override controls casting only; it does not supply Zod output validation.

For a whole-object transform, finish with .pipe(z.object({...})) so conversion can determine the stored fields. Built-in string setters such as .trim() and .toLowerCase() continue to normalize on Mongoose assignment.

Choose input parsing or Mongoose casting

Direct construction keeps native Mongoose casting. For example, a number field or a number/boolean union may turn '1' into 1 before document validation. Call your Zod schema's parse() first when raw input must satisfy Zod's rules. Explicit Zod coercion also belongs at that boundary.

Disable the extra Zod validation

schema-options.ts
const mongooseSchema = toMongooseSchema(BookingZodSchema, {
  validateBeforeSave: false,
});

This option skips the package's Zod validation hook. Mongoose's own validation still runs. You can also set validateBeforeSave: false in top-level withMongoose metadata. See Core Functions for the option signature.