typegoose-patterns

2
0
Source

MX Space project TypeGoose model patterns. Apply when creating data models, defining schemas, or handling MongoDB operations.

Install

mkdir -p .claude/skills/typegoose-patterns && curl -L -o skill.zip "https://mcp.directory/api/skills/download/3907" && unzip -o skill.zip -d .claude/skills/typegoose-patterns && rm skill.zip

Installs to .claude/skills/typegoose-patterns

About this skill

TypeGoose Model Patterns

Basic Model

import { modelOptions, prop, Severity, index } from '@typegoose/typegoose'
import { BaseModel } from '~/shared/model/base.model'

export const MY_COLLECTION_NAME = 'my_items'

@modelOptions({
  options: {
    customName: MY_COLLECTION_NAME,
    allowMixed: Severity.ALLOW,
  },
})
export class MyModel extends BaseModel {
  @prop({ required: true })
  name!: string

  @prop()
  description?: string
}

Base Model Inheritance

// BaseModel - Base fields
// Includes: _id, created, updated

// WriteBaseModel - Content models
// Includes: title, text, images, meta, modified
export class PostModel extends WriteBaseModel {
  // Additional fields
}

// BaseCommentIndexModel - Supports comments
// Includes: commentsIndex, allowComment

Field Decorators

Basic Fields

@prop({ required: true })        // Required
name!: string

@prop()                          // Optional
description?: string

@prop({ default: true })         // Default value
isPublished: boolean

@prop({ unique: true })          // Unique constraint
slug!: string

@prop({ trim: true })            // Auto trim
title!: string

Indexes

// Single field index
@prop({ index: true })
slug!: string

// Class-level indexes
@index({ slug: 1 })
@index({ created: -1 })
@index({ title: 'text', text: 'text' })  // Text index
export class MyModel extends BaseModel {}

References

import { Ref } from '@typegoose/typegoose'
import { Category } from '~/modules/category/category.model'

// Reference field
@prop({ ref: () => Category, required: true })
categoryId: Ref<Category>

// Auto-populated virtual field
@prop({
  ref: () => Category,
  foreignField: '_id',
  localField: 'categoryId',
  justOne: true,
  autopopulate: true,
})
public category: Ref<Category>

Nested Objects

// Define subdocument class
class Count {
  @prop({ default: 0 })
  read: number

  @prop({ default: 0 })
  like: number
}

// Usage
@prop({ type: Count, default: { read: 0, like: 0 }, _id: false })
count: Count

Arrays

@prop({ type: () => [String] })
tags?: string[]

@prop({ type: () => [ImageModel] })
images?: ImageModel[]

Plugins

import { plugin } from '@typegoose/typegoose'
import mongoosePaginate from 'mongoose-paginate-v2'
import aggregatePaginate from 'mongoose-aggregate-paginate-v2'
import autoPopulate from 'mongoose-autopopulate'

@plugin(mongoosePaginate)      // Pagination
@plugin(aggregatePaginate)     // Aggregate pagination
@plugin(autoPopulate)          // Auto populate
export class MyModel extends BaseModel {}

Protected Keys

export class MyModel extends BaseModel {
  @prop()
  secret?: string

  // Define fields that should not be directly updated
  static get protectedKeys() {
    return ['secret'].concat(super.protectedKeys)
  }
}

Model Registration

In apps/core/src/processors/database/database.models.ts:

import { MyModel } from '~/modules/my/my.model'

export const databaseModels = [
  // ...
  MyModel,
]

Usage in Services

import { InjectModel } from '~/transformers/model.transformer'
import type { ReturnModelType } from '@typegoose/typegoose'
import type { AggregatePaginateModel } from '~/shared/types/mongoose.types'

@Injectable()
export class MyService {
  constructor(
    @InjectModel(MyModel)
    private readonly model: ReturnModelType<typeof MyModel> &
      AggregatePaginateModel<MyModel>,
  ) {}

  // Query - use lean() to return plain object
  async findById(id: string) {
    return this.model.findById(id).lean()
  }

  // Pagination
  async paginate(page: number, size: number) {
    return this.model.paginate({}, { page, limit: size })
  }

  // Aggregate pagination
  async aggregatePaginate(pipeline: any[], page: number, size: number) {
    const aggregate = this.model.aggregate(pipeline)
    return this.model.aggregatePaginate(aggregate, { page, limit: size })
  }
}

Common Query Patterns

// Conditional query
await this.model.find({ isPublished: true }).lean()

// Sorting
await this.model.find().sort({ created: -1 }).lean()

// Field selection
await this.model.find().select('title slug').lean()

// Population
await this.model.find().populate('category').lean()

// Count
await this.model.countDocuments({ isPublished: true })

// Update
await this.model.findByIdAndUpdate(id, data, { new: true }).lean()

// Delete
await this.model.findByIdAndDelete(id)

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.