Turns JSON into a NestJS @nestjs/mongoose schema class: a @Schema() class with @Prop() on every field, the schema built with SchemaFactory.createForClass(), and a ProductDocument type, all in one file. Each field also carries class-validator's @IsNotEmpty() or @IsOptional().
Use it when a NestJS module needs a schema to register with MongooseModule.forFeature(), you already have a sample of the document to store, and writing every decorator by hand is the slow part.
Model name (default MyModel). Typing product produces Product, ProductDocument and ProductSchema.product.schema.ts and register it with MongooseModule.forFeature([{ name: Product.name, schema: ProductSchema }]).{
"sku": "KB-87-RED",
"title": "Mechanical keyboard",
"price": 89.5,
"stock": 42,
"discontinued": false,
"restocked_at": "2024-03-18"
}import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Schema as MongooseSchema } from 'mongoose';
import { IsNotEmpty, IsOptional } from 'class-validator';
export type ProductDocument = Product & Document;
@Schema()
export class Product {
_id: MongooseSchema.Types.ObjectId;
@Prop({ type: MongooseSchema.Types.String, required: true })
@IsNotEmpty()
sku: string;
@Prop({ type: MongooseSchema.Types.String, required: true })
@IsNotEmpty()
title: string;
@Prop({ type: MongooseSchema.Types.Number, required: true })
@IsNotEmpty()
price: number;
@Prop({ type: MongooseSchema.Types.Number, required: true })
@IsNotEmpty()
stock: number;
@Prop({ type: MongooseSchema.Types.Boolean, required: true })
@IsNotEmpty()
discontinued: boolean;
@Prop({ type: MongooseSchema.Types.Date, required: true })
@IsNotEmpty()
restocked_at: Date;
}
export const ProductSchema = SchemaFactory.createForClass(Product);The sample is a single, fully filled document, so every field gets required: true and @IsNotEmpty(). restocked_at is a date-formatted string, so it is typed Date, and the property keeps the stored key name restocked_at.
@Prop({ type: MongooseSchema.Types.String, required: true }). Mongoose's Schema is imported as MongooseSchema so it does not clash with the Schema decorator.number, boolean, Date for ISO 8601 date strings, string for everything else including digit-only strings like "0042".MongooseSchema.Types.Mixed and typed Record<string, unknown>; arrays of one plain type become e.g. [MongooseSchema.Types.String] with string[].'home-url': string), so the class matches documents already in the collection.required: true plus @IsNotEmpty(); the rest get only @IsOptional(). An _id key in the input is skipped because _id: MongooseSchema.Types.ObjectId is already declared.export type ProductDocument = Product & Document is generated for injection like @InjectModel(Product.name) model: Model<ProductDocument>.Feed in an event payload another team sent you, or the JSON from a scraper, to get the schema class, then inject it with @InjectModel and call create or find right away.
Export a few documents saved by the old new Schema({...}) model and paste them here to rewrite it as a decorator-based class without dropping fields while copying them over by hand.
@IsNotEmpty() and @IsOptional() sit on the schema class, but ValidationPipe validates controller DTOs. To validate requests, move these decorators to a DTO class or create one.@Schema() has no options, so the collection name follows Mongoose's rule of lowercasing and pluralizing the model name: products. Set @Schema({ collection: 'product' }) if you need a specific name.? (e.g. memo: string). With strictNullChecks, changing them to memo?: string is safer.Mixed rather than typed schemas. For validation inside them, define a separate @Schema() class and use @Prop({ type: SubSchema }).& Document instead of extending Document?It follows the default NestJS docs pattern: the schema class stays a plain field definition and ProductDocument is used only where Mongoose document methods like save() are needed. On Mongoose 7+, HydratedDocument<Product> is a drop-in alternative.
Delete the import { IsNotEmpty, IsOptional } from 'class-validator' line and the two decorators on each field. Schema behavior is controlled by required in @Prop() alone.
type in @Prop()?With emitDecoratorMetadata, simple types can be inferred, but inference fails for arrays and unions such as Date | null. The generated code states type up front so behavior stays the same when you later change a property's TypeScript type.