Convert JSON to Mongoose Schema (TypeScript)!

Input JSON to generate NestJS @nestjs/mongoose schemas (@Schema, @Prop, SchemaFactory) for MongoDB!
JSON
Result
 

Convert JSON to Mongoose Schema (TypeScript)!

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.

How to use

  1. Paste a sample document into the input. If some fields are only sometimes present, paste several documents as an array so optional fields are detected.
  2. Enter the class name in Model name (default MyModel). Typing product produces Product, ProductDocument and ProductSchema.
  3. Save the result as product.schema.ts and register it with MongooseModule.forFeature([{ name: Product.name, schema: ProductSchema }]).

Example

Input (JSON)
{
  "sku": "KB-87-RED",
  "title": "Mechanical keyboard",
  "price": 89.5,
  "stock": 42,
  "discontinued": false,
  "restocked_at": "2024-03-18"
}
Output (NestJS @nestjs/mongoose)
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.

Supported features

  • Mongoose types are explicit, e.g. @Prop({ type: MongooseSchema.Types.String, required: true }). Mongoose's Schema is imported as MongooseSchema so it does not clash with the Schema decorator.
  • TypeScript types: number, boolean, Date for ISO 8601 date strings, string for everything else including digit-only strings like "0042".
  • Nested objects are declared with MongooseSchema.Types.Mixed and typed Record<string, unknown>; arrays of one plain type become e.g. [MongooseSchema.Types.String] with string[].
  • Property names are the JSON keys unchanged, quoted when needed ('home-url': string), so the class matches documents already in the collection.
  • Fields with a non-empty value in every document get 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>.

Use cases

Adding a collection to a NestJS service

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.

Moving an Express Mongoose model to NestJS

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.

Notes and limitations

  • @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.
  • Optional fields still come out without ? (e.g. memo: string). With strictNullChecks, changing them to memo?: string is safer.
  • Sub-documents are stored as Mixed rather than typed schemas. For validation inside them, define a separate @Schema() class and use @Prop({ type: SubSchema }).

FAQ

Why & 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.

What if my project does not use class-validator?

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.

Do I have to specify 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.