Guides
Strict Model
Infer populated reference types in Mongoose queries and documents with toStrictModel.
Strict Model
Use toStrictModel() to make .populate() update the TypeScript result type. It infers types from your schema, including methods and query helpers.
Create the model
Define references with zRef() and register their models before querying. These examples require an active MongoDB connection; see References and population for the basics.
strict-post.ts
import mongoose from 'mongoose';
import {z} from 'zod/v4';
import {toMongooseSchema, toStrictModel, zRef} from '@nullix/zod-mongoose';
const UserSchema = z.object({username: z.string()});
const AuthorSchema = z.object({
name: z.string(),
user: zRef('Account', UserSchema),
});
const PostSchema = z.object({
title: z.string(),
author: zRef('Author', AuthorSchema),
mentions: z.array(zRef('Author', AuthorSchema)),
});
mongoose.model('Account', toMongooseSchema(UserSchema));
mongoose.model('Author', toMongooseSchema(AuthorSchema));
const PostModel = toStrictModel('Post', toMongooseSchema(PostSchema));
Populate a reference
Continue from the model above. Query methods such as sort() and select() preserve population inference.
const post = await PostModel.findOne()
.sort({title: 1})
.populate('author')
.exec();
if (post?.author) {
console.log(post.author.name); // string
}
Document .populate() works too, including on documents returned by create():
const draft = await PostModel.findOne().exec();
if (draft) {
const populated = await draft.populate('author');
console.log(populated.author.name);
}
Literal paths must refer to zRef() fields. For example, .populate('title') is a type error.
Populate several or nested references
Use an options array to express nested population in one place:
const postWithAuthors = await PostModel.findOne().populate([
{path: 'author', populate: {path: 'user'}},
{path: 'mentions'},
]).exec();
if (postWithAuthors?.author?.user) {
console.log(postWithAuthors.author.user.username);
console.log(postWithAuthors.mentions[0]?.name);
}
For reusable options, lean(), schema extensions, and explicit generics, see TypeScript details.