v3.6.0
Playground
Guides

TypeScript Details

Keep inference when reusing options, adding Mongoose helpers, using lean queries, or declaring explicit model types.

TypeScript Details

Most applications can let toMongooseSchema() and toStrictModel() infer their types. This page covers the cases where you need more control. Population examples build on the models in Strict Model.

Reuse population options

Inline options arrays infer each requested path. For a reusable variable, keep its literal paths with as const and check them with satisfies:

import type {PopulateOptions} from '@nullix/zod-mongoose';

const options = [
  {path: 'author', populate: [{path: 'user'}]},
  {path: 'mentions'},
] as const satisfies PopulateOptions<z.infer<typeof PostSchema>>;

const post = await PostModel.findOne().populate(options).exec();

Arrays assembled dynamically may be empty or contain only some paths. Their result types therefore allow reference IDs as well as populated documents. Literal string paths are validated; a runtime string cannot provide the same inference.

Keep query result types

Ordinary fluent methods such as where(), sort(), limit(), and select() retain strict population inference. orFail() removes null from a single-document result.

lean() returns plain objects, including for populated references. You can call it before or after population:

const post = await PostModel.findOne()
  .lean()
  .populate({path: 'author', populate: {path: 'user'}})
  .orFail();

console.log(post.author.user.username);
// post.save() is a type error: this is a plain object.

An explicit select<Shape>() or lean<Shape>() opts into your supplied result shape. These calls use Mongoose's query types for subsequent operations. Apply strict population before an explicit result override, and include the selected populated fields in that shape. A string projection alone does not prove which fields are present.

transform(), counts, and distinct queries retain their own result types. They do not turn back into documents.

Understand repeated population

Prefer one entry per root path with its nested options together. When paths repeat, inference follows Mongoose:

OperationRepeated root path
Query options or chained query callsCombines nested population when both entries provide it
Document options arrayUses the last entry
A later entry without nested populationReplaces the earlier nested options

Strict document population is available on query results, constructed and hydrated documents, and hydrated results from create(), insertOne(), and insertMany(). Native overloads for aggregate errors and lean or raw insert results remain available.

Infer generated schema fields

Literal schema options determine generated timestamps, IDs, the id virtual, and version keys. Zod's own input and output types stay unchanged.

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

const UserSchema = z.object({name: z.string()});
const UserModel = mongoose.model('TimestampedUser', toMongooseSchema(UserSchema, {
  timestamps: {createdAt: 'created_on', updatedAt: false},
  versionKey: 'revision',
}));

const user = await UserModel.create({name: 'Ada'});
console.log(user.created_on); // Date
console.log(user.revision);   // number

_id: false and id: false remove generated fields from the document type. An _id explicitly declared in Zod is preserved. Timestamps and version keys are initialized when Mongoose saves a document; their inferred types do not mean they already exist on a freshly constructed document.

For options stored in a variable, use as const satisfies ToMongooseSchemaOptions<YourDocument> to preserve literals. A broad type annotation can lose that information.

The value returned by withMongoose(schema, metadata) also carries literal metadata into conversion. Explicit conversion options override that metadata. TypeScript cannot infer later registry mutations, arbitrary .meta() values, or fields added by plugins; use explicit conversion options or explicit document types for those cases.

Preserve schema extensions

Inline methods, statics, and query helpers infer from the Zod document:

const postSchema = toMongooseSchema(PostSchema, {
  query: {
    byTitle(title: string) {
      return this.where({title});
    },
  },
});
const TypedPostModel = toStrictModel('TypedPost', postSchema);
const posts = await TypedPostModel.find().byTitle('Hello').populate('author').exec();

Inline fluent helpers retain the current population state. Helpers with explicitly declared return types keep those signatures, including projections and terminal results. Use the generics on ToMongooseSchemaOptions when you need declared helper interfaces, virtuals, or custom hydrated document types, such as Mongoose document arrays.

Existing toStrictModel<Post>(name, schema) calls remain supported. TypeScript cannot infer omitted generic arguments once you supply the first one. Pass both types to retain schema extensions with an explicit document type:

const ExplicitPostModel = toStrictModel<z.infer<typeof PostSchema>, typeof postSchema>(
  'ExplicitPost',
  postSchema,
);

StrictDocument, StrictQuery, and StrictModel are exported for advanced integrations. Prefer inference from the schema in application code.