Specialized Helpers
Specialized Helpers
Mongoose provides several specialized types, such as ObjectId and Buffer. @nullix/zod-mongoose includes dedicated helpers to easily define these types in your Zod schemas.
zObjectId(options?)
Helper to create a Zod schema representing a Mongoose ObjectId.
- options: Optional
MongooseMetafor this field.
By default, zObjectId() creates a required Zod field (unless .optional() is used) but omits the field from the generated Mongoose schema. This allows Mongoose to manage the automatic generation and internal lifecycle of the _id field without conflicts.
import { z } from 'zod/v4';
import { zObjectId } from '@nullix/zod-mongoose';
const UserZodSchema = z.object({
_id: zObjectId(), // Required for Zod validation, omitted from Mongoose schema
name: z.string(),
});
To explicitly define the _id field in the Mongoose schema (e.g., to add an index, a custom getter, or to disable auto-generation), use the includeId: true flag.
const CustomIdSchema = z.object({
_id: zObjectId({ includeId: true, index: true }),
});
Population
Mongoose allows you to reference documents in other collections using ObjectIds. @nullix/zod-mongoose provides a comprehensive way to handle these references, ensuring type-safety and validation for both unpopulated (ID) and populated (object) states.
zRef(ref, schema, options?)
Helper for fields that can be either an ObjectId (unpopulated) or a populated object.
- ref: The name of the Mongoose model being referenced.
- schema: The Zod schema representing the populated object.
- options: Optional
MongooseMetafor this field.
During Zod validation, zRef accepts either an ObjectId or a full object that matches the provided schema. If an object is provided, it must contain an _id field, which will be extracted. The output of the Zod validation is always an ObjectId (or its string representation in frontend mode, which is automatically enabled in browser environments).
const UserSchema = z.object({ _id: z.string(), name: z.string() });
const PostSchema = z.object({
author: zRef('User', UserSchema),
});
// Both are valid, but output is always an ID
PostSchema.parse({ author: '507f1f77...' }); // { author: '507f1f77...' }
PostSchema.parse({ author: { _id: '507f1f77...', name: 'John' } }); // { author: '507f1f77...' }
PopulatedSchema<T, K>
TypeScript utility type to extract the populated object type from a Zod schema. This is the primary tool for typing Mongoose results after calling .populate().
- T: The Zod schema (e.g.,
typeof PostSchema) or an inferred type. - K: The key(s) to populate. If omitted, all
zReffields will be populated recursively.
import { PopulatedSchema } from '@nullix/zod-mongoose';
// 1. Get the type for all reference fields
type FullPost = PopulatedSchema<typeof PostSchema>;
// 2. Use it with Mongoose to get full type-safety
const post = await Post.findOne().populate<FullPost>('author').exec();
console.log(post.author.name); // Type-safe!
populateZodSchema(schema, keys?)
Runtime helper to create a new Zod schema where specific zRef fields are replaced by their underlying refSchema. This is useful when you want to validate already-populated data (e.g., in a frontend application or an API endpoint that receives populated objects).
- schema: The Zod schema to populate.
- keys: Optional array of keys to populate. If omitted, all
zReffields will be populated recursively.
import { populateZodSchema } from '@nullix/zod-mongoose';
// Create a schema that expects full User objects instead of IDs
const PopulatedPostSchema = populateZodSchema(PostSchema);
// This will now validate the author object
const validated = PopulatedPostSchema.parse(dataFromApi);
zBuffer(options?)
Helper to create a Zod schema representing a Mongoose Buffer.
- options: Optional
MongooseMetafor this field.
import { zBuffer } from '@nullix/zod-mongoose';
const ProductSchema = z.object({
imageData: zBuffer({ required: true }),
});
genTimestampsSchema(createdAtField?, updatedAtField?)
Returns a plain object (Zod shape) with timestamp fields. This allows for easy spreading into z.object().
- createdAtField: Name of the "created at" field (default:
createdAt). - updatedAtField: Name of the "updated at" field (default:
updatedAt).
Pass null as a name to disable a specific field.
import { z } from 'zod/v4';
import { genTimestampsSchema, withMongoose } from '@nullix/zod-mongoose';
const userSchema = withMongoose(
z.object({
...genTimestampsSchema(),
name: z.string(),
}),
{ timestamps: true }
);
const mongooseSchema = toMongooseSchema(userSchema);
// Resulting Mongoose schema will have { timestamps: true } automatically.
Utility Types
@nullix/zod-mongoose provides several utility types for manual type inference and document typing.
InferMongoose<T>
An alias for OutputMongoose<T>. This is the recommended type to use when you want to manually infer the output type of a Mongoose document from a Zod schema.
OutputMongoose<T>
Infers the output type of a Mongoose document. It takes a Zod schema T and returns the inferred output type, ensuring that an _id field of type mongoose.Types.ObjectId is always included.
import { OutputMongoose } from '@nullix/zod-mongoose';
type UserDocument = OutputMongoose<typeof UserZodSchema>;
InputMongoose<T>
Infers the input type for a Zod schema, equivalent to z.input<T>.
import { InputMongoose } from '@nullix/zod-mongoose';
type UserInput = InputMongoose<typeof UserZodSchema>;