Typegoose for TypeScript: Complete Guide
\n\nTypegoose 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\nWhy 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\nTypegoose 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\nInstallation
\n\nTo install Typegoose and its dependencies, run in the terminal:
\n\nnpm install @typegoose/typegoose mongoose\nnpm install -D @types/mongoose\n\nIf you are using yarn:
\n\nyarn add @typegoose/typegoose mongoose\nyarn add -D @types/mongoose\n\nTypegoose requires TypeScript version 4.0 or higher. Make sure the following options are enabled in your tsconfig.json:
{\n "compilerOptions": {\n "experimentalDecorators": true,\n "emitDecoratorMetadata": true,\n "target": "ES2020",\n "module": "commonjs"\n }\n}\n\nQuick Start
\n\nLet's create a simple user model and save it to MongoDB.
\n\nimport { 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\nThis 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.
Main Methods and Functions
\n\n1. @prop() — Property Decorator
\nSignature: @prop(options?: PropOptions)
Description: Defines a field in the Mongoose schema. Accepts an options object similar to Mongoose field options (required, default, unique, ref, enum, etc.).
\n\nimport { 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 Also in library
Kotlin Task Scheduler: Overview and Usage Examples
Serilog for C# (.NET): Complete Guide with Examples
Working with Excel in Swift on iOS and macOS: Libraries and Examples