JSON을 mongoose schema(typescript)로 변환하세요!

JSON을 입력하면 NestJS @nestjs/mongoose 스키마(@Schema, @Prop, SchemaFactory)로 변환합니다! MongoDB 프로젝트에.
JSON
결과
 

JSON을 mongoose schema(typescript)로 변환하세요!

JSON을 NestJS @nestjs/mongoose 스키마 클래스로 바꿉니다. 필드마다 @Prop()이 붙은 @Schema() 클래스, SchemaFactory.createForClass()로 만든 스키마, ProductDocument 타입이 한 파일에 담기고, 각 필드에는 class-validator의 @IsNotEmpty() 또는 @IsOptional()도 붙습니다.

NestJS 모듈에서 MongooseModule.forFeature()에 등록할 스키마가 필요한데 저장할 문서 샘플은 이미 있고, 데코레이터를 하나하나 손으로 쓰는 게 번거로울 때 쓰면 됩니다.

사용 방법

  1. 입력 칸에 샘플 문서를 붙여넣습니다. 가끔만 있는 필드가 있다면 문서 여러 개를 배열로 넣어야 선택 필드가 구분됩니다.
  2. 모델 이름에 클래스 이름을 적습니다(기본값 MyModel). product라고 쓰면 Product, ProductDocument, ProductSchema가 만들어집니다.
  3. 결과를 product.schema.ts로 저장하고 MongooseModule.forFeature([{ name: Product.name, schema: ProductSchema }])로 등록합니다.

예시

입력 (JSON)
{
  "sku": "KB-87-RED",
  "title": "Mechanical keyboard",
  "price": 89.5,
  "stock": 42,
  "discontinued": false,
  "restocked_at": "2024-03-18"
}
출력 (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);

값이 모두 채워진 문서 하나라서 모든 필드에 required: true와 @IsNotEmpty()가 붙었습니다. restocked_at은 날짜 형식 문자열이라 Date 타입이 되고, 속성 이름은 저장된 키 그대로 restocked_at입니다.

지원 기능

  • @Prop({ type: MongooseSchema.Types.String, required: true })처럼 Mongoose 타입을 명시합니다. Schema 데코레이터와 이름이 겹치지 않도록 mongoose의 Schema는 MongooseSchema로 가져옵니다.
  • TypeScript 타입: number, boolean, ISO 8601 날짜 문자열은 Date, 나머지는 string입니다. "0042"처럼 숫자만 든 문자열도 string입니다.
  • 중첩 객체는 MongooseSchema.Types.Mixed와 Record<string, unknown>으로, 한 종류의 단순 값 배열은 [MongooseSchema.Types.String]과 string[]처럼 선언합니다.
  • 속성 이름은 JSON 키를 바꾸지 않고 쓰며 필요하면 따옴표로 감쌉니다('home-url': string). 그래서 컬렉션에 이미 있는 문서와 그대로 맞습니다.
  • 모든 문서에 비어 있지 않은 값이 있는 필드에는 required: true와 @IsNotEmpty(), 나머지에는 @IsOptional()만 붙습니다. 입력의 _id 키는 _id: MongooseSchema.Types.ObjectId가 이미 선언돼 있어 건너뜁니다.
  • @InjectModel(Product.name) model: Model<ProductDocument>처럼 주입할 때 쓰도록 export type ProductDocument = Product & Document를 만듭니다.

사용 사례

NestJS 서비스에 컬렉션 추가

다른 팀이 보내 준 이벤트 페이로드나 스크래퍼가 만든 JSON을 넣어 스키마 클래스를 만들고, @InjectModel로 주입해 바로 create, find를 호출할 수 있습니다.

Express의 Mongoose 모델을 NestJS로 옮길 때

기존 new Schema({...}) 모델로 저장된 문서 몇 개를 내보내 붙여넣으면, 손으로 옮기다 필드를 빠뜨리는 일 없이 데코레이터 기반 클래스로 다시 쓸 수 있습니다.

주의사항

  • @IsNotEmpty(), @IsOptional()은 스키마 클래스에 붙지만 ValidationPipe가 검사하는 대상은 컨트롤러의 DTO입니다. 요청을 검증하려면 이 데코레이터를 DTO 클래스로 옮기거나 DTO를 따로 만드세요.
  • @Schema()에 옵션이 없어서 컬렉션 이름은 모델 이름을 소문자 복수형으로 바꾼 products가 됩니다. 이름을 정해야 한다면 @Schema({ collection: 'product' })로 지정하세요.
  • 선택 필드도 ? 없이 나옵니다(예: memo: string). strictNullChecks를 쓴다면 memo?: string으로 바꾸는 편이 안전합니다.
  • 하위 문서는 타입이 정해진 스키마가 아니라 Mixed로 저장됩니다. 내부 값까지 검증하려면 별도의 @Schema() 클래스를 만들어 @Prop({ type: SubSchema })로 연결하세요.

자주 묻는 질문

Document를 상속하지 않고 & Document를 쓰는 이유는요?

NestJS 공식 문서의 기본 패턴을 따른 것입니다. 스키마 클래스는 필드 정의만 하고, save() 같은 Mongoose 문서 메서드가 필요한 곳에서만 ProductDocument를 씁니다. Mongoose 7 이상이라면 HydratedDocument<Product>로 바꿔 써도 됩니다.

class-validator를 쓰지 않는 프로젝트라면요?

import { IsNotEmpty, IsOptional } from 'class-validator' 줄과 각 필드의 데코레이터 두 줄을 지우면 됩니다. 스키마 동작은 @Prop()의 required만으로 정해집니다.

@Prop()에 type을 꼭 써야 하나요?

emitDecoratorMetadata가 켜져 있으면 단순 타입은 추론되지만, 배열이나 Date | null 같은 유니언은 추론에 실패합니다. 생성 코드는 처음부터 type을 적어 두므로 나중에 TypeScript 타입을 바꿔도 동작이 달라지지 않습니다.