Chuyển đổi JSON thành Mongoose (TypeScript)!

Nhập JSON và chuyển đổi nó thành Mongoose (TypeScript)! Hỗ trợ NestJS @nestjs/mongoose @Schema, @Prop, SchemaFactory, MongoDB.
JSON
Kết quả
 

Chuyển đổi JSON thành Mongoose (TypeScript)!

Biến JSON thành class schema @nestjs/mongoose của NestJS: một class @Schema() với @Prop() trên mọi field, schema được dựng bằng SchemaFactory.createForClass(), và một type ProductDocument, tất cả trong một file. Mỗi field còn mang @IsNotEmpty() hoặc @IsOptional() của class-validator.

Dùng nó khi một module NestJS cần schema để đăng ký với MongooseModule.forFeature(), bạn đã có sẵn mẫu document cần lưu, và việc viết tay từng decorator là phần tốn thời gian.

Cách sử dụng

  1. Dán một document mẫu vào ô nhập. Nếu có field chỉ thỉnh thoảng xuất hiện, hãy dán nhiều document dưới dạng mảng để field tùy chọn được phát hiện.
  2. Nhập tên class vào Tên model (mặc định MyModel). Gõ product sẽ tạo ra Product, ProductDocument và ProductSchema.
  3. Lưu kết quả thành product.schema.ts và đăng ký bằng MongooseModule.forFeature([{ name: Product.name, schema: ProductSchema }]).

Ví dụ

Đầu vào (JSON)
{
  "sku": "KB-87-RED",
  "title": "Mechanical keyboard",
  "price": 89.5,
  "stock": 42,
  "discontinued": false,
  "restocked_at": "2024-03-18"
}
Đầu ra (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);

Mẫu là một document duy nhất được điền đầy đủ, nên mọi field đều nhận required: true và @IsNotEmpty(). restocked_at là chuỗi có định dạng ngày nên có kiểu Date, và property giữ tên key đã lưu restocked_at.

Tính năng hỗ trợ

  • Kiểu Mongoose được ghi tường minh, ví dụ @Prop({ type: MongooseSchema.Types.String, required: true }). Schema của Mongoose được import dưới tên MongooseSchema để không xung đột với decorator Schema.
  • Kiểu TypeScript: number, boolean, Date cho chuỗi ngày ISO 8601, string cho mọi thứ còn lại, kể cả chuỗi chỉ gồm chữ số như "0042".
  • Object lồng nhau được khai báo bằng MongooseSchema.Types.Mixed với kiểu Record<string, unknown>; mảng của một kiểu đơn thành ví dụ [MongooseSchema.Types.String] với string[].
  • Tên property là key JSON giữ nguyên, có dấu nháy khi cần ('home-url': string), nên class khớp với các document đã có trong collection.
  • Field có giá trị không rỗng ở mọi document nhận required: true cộng @IsNotEmpty(); số còn lại chỉ nhận @IsOptional(). Key _id trong đầu vào bị bỏ qua vì _id: MongooseSchema.Types.ObjectId đã được khai báo.
  • export type ProductDocument = Product & Document được tạo để inject kiểu @InjectModel(Product.name) model: Model<ProductDocument>.

Trường hợp sử dụng

Thêm collection vào service NestJS

Đưa vào payload event mà đội khác gửi cho bạn, hoặc JSON từ scraper, để có class schema, rồi inject bằng @InjectModel và gọi create hay find ngay.

Chuyển model Mongoose của Express sang NestJS

Export vài document được lưu bởi model new Schema({...}) cũ rồi dán vào đây để viết lại thành class dùng decorator mà không sót field nào như khi chép tay.

Lưu ý và giới hạn

  • @IsNotEmpty() và @IsOptional() nằm trên class schema, nhưng ValidationPipe validate DTO của controller. Để validate request, hãy chuyển các decorator này sang class DTO hoặc tạo một class mới.
  • @Schema() không có option, nên tên collection theo quy tắc của Mongoose là chuyển tên model về chữ thường và số nhiều: products. Đặt @Schema({ collection: 'product' }) nếu cần tên cụ thể.
  • Field tùy chọn vẫn ra không có ? (ví dụ memo: string). Với strictNullChecks, đổi thành memo?: string sẽ an toàn hơn.
  • Sub-document được lưu dưới dạng Mixed thay vì schema có kiểu. Để validate bên trong chúng, hãy định nghĩa một class @Schema() riêng và dùng @Prop({ type: SubSchema }).

Câu hỏi thường gặp

Vì sao dùng & Document thay vì kế thừa Document?

Nó theo mẫu mặc định trong tài liệu NestJS: class schema vẫn chỉ là định nghĩa field thuần, còn ProductDocument chỉ được dùng ở chỗ cần method của document Mongoose như save(). Trên Mongoose 7+, HydratedDocument<Product> là lựa chọn thay thế tương đương.

Nếu dự án không dùng class-validator thì sao?

Xóa dòng import { IsNotEmpty, IsOptional } from 'class-validator' và hai decorator trên mỗi field. Hành vi của schema chỉ do required trong @Prop() quyết định.

Có bắt buộc ghi type trong @Prop() không?

Với emitDecoratorMetadata, kiểu đơn giản có thể được suy ra, nhưng việc suy ra thất bại với mảng và union như Date | null. Code được tạo ghi rõ type ngay từ đầu để hành vi không đổi khi sau này bạn sửa kiểu TypeScript của property.