Typegoose for TypeScript: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Typegoose for TypeScript: Complete Guide

\n\n

Typegoose is a powerful wrapper library for Mongoose that allows you to define MongoDB models using TypeScript classes and decorators. It solves a key problem in Node.js development: the mismatch between TypeScript's strict typing and Mongoose's dynamic nature. Instead of manually duplicating types and schemas, Typegoose lets you describe the model once — as a TypeScript class — and automatically generates a Mongoose schema from it.

\n\n

Why is this needed? First, it significantly reduces the amount of boilerplate code. You no longer need to write a separate interface and a separate schema — the TypeScript class serves both purposes. Second, Typegoose ensures complete type safety at all stages: from document creation to query execution. The IDE will suggest fields, methods, and their types, virtually eliminating errors related to typos in field names or incorrect data types. Third, the library supports all Mongoose features: virtual fields, hooks (pre/post), indexes, populate, and middleware.

\n\n

Typegoose is ideal for large projects where code maintainability is important, as well as for teams that want to leverage all the benefits of OOP in TypeScript. It integrates easily with NestJS, Express, and other frameworks, providing a unified standard for data description.

\n\n

Installation

\n\n

To install Typegoose and its dependencies, run in the terminal:

\n\n
npm install @typegoose/typegoose mongoose\nnpm install -D @types/mongoose
\n\n

If you are using yarn:

\n\n
yarn add @typegoose/typegoose mongoose\nyarn add -D @types/mongoose
\n\n

Typegoose requires TypeScript version 4.0 or higher. Make sure the following options are enabled in your tsconfig.json:

\n\n
{\n  "compilerOptions": {\n    "experimentalDecorators": true,\n    "emitDecoratorMetadata": true,\n    "target": "ES2020",\n    "module": "commonjs"\n  }\n}
\n\n

Quick Start

\n\n

Let's create a simple user model and save it to MongoDB.

\n\n
import { prop, getModelForClass } from '@typegoose/typegoose';\nimport mongoose from 'mongoose';\n\n// 1. Define the model class\nclass User {\n  @prop({ required: true })\n  public name!: string;\n\n  @prop({ required: true, unique: true })\n  public email!: string;\n\n  @prop({ default: 0 })\n  public age!: number;\n}\n\n// 2. Get the Mongoose model\nconst UserModel = getModelForClass(User);\n\n// 3. Connect to the database and work\nasync function main() {\n  await mongoose.connect('mongodb://localhost:27017/test');\n\n  // Create a user\n  const user = await UserModel.create({\n    name: 'Alice',\n    email: 'alice@example.com',\n    age: 30,\n  });\n\n  console.log('Created:', user);\n\n  // Find a user\n  const found = await UserModel.findOne({ email: 'alice@example.com' });\n  console.log('Found:', found);\n}\n\nmain().catch(console.error);
\n\n

This minimal example demonstrates the core idea: the User class with the @prop decorator describes the schema, and the getModelForClass function creates a ready-to-use Mongoose model.

\n\n

Main Methods and Functions

\n\n

1. @prop() — Property Decorator

\n

Signature: @prop(options?: PropOptions)

\n

Description: Defines a field in the Mongoose schema. Accepts an options object similar to Mongoose field options (required, default, unique, ref, enum, etc.).

\n\n
import { prop } from '@typegoose/typegoose';\n\nclass Product {\n  @prop({ required: true, type: String })\n  public title!: string;\n\n  @prop({ default: 0, min: 0 })\n  public price!: number;\n\n  @prop({ enum: ['a                    

Recommendations