将 JSON 转换为 Mongoose(TypeScript)方案!

输入 JSON 并将其转换为 Mongoose(TypeScript)方案!支持 NestJS @nestjs/mongoose @Schema, @Prop, SchemaFactory, MongoDB。
JSON
结果
 

将 JSON 转换为 Mongoose(TypeScript)方案!

把 JSON 转换成 NestJS @nestjs/mongoose 的 schema 类:一个每个字段都带 @Prop() 的 @Schema() 类、用 SchemaFactory.createForClass() 构建的 schema,以及 ProductDocument 类型,全部放在一个文件里。每个字段还带有 class-validator 的 @IsNotEmpty() 或 @IsOptional()。

当 NestJS 模块需要一个 schema 来注册到 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,属性保留存储时的 key 名 restocked_at。

支持的功能

  • Mongoose 类型是显式写出的,例如 @Prop({ type: MongooseSchema.Types.String, required: true })。Mongoose 的 Schema 以 MongooseSchema 的名义导入,以免与 Schema 装饰器冲突。
  • TypeScript 类型:number、boolean,ISO 8601 日期字符串为 Date,其他一律为 string,包括 "0042" 这样的纯数字字符串。
  • 嵌套对象用 MongooseSchema.Types.Mixed 声明,类型为 Record<string, unknown>;单一基本类型的数组变成 [MongooseSchema.Types.String] 配合 string[] 这样的形式。
  • 属性名就是原样的 JSON key,必要时加引号('home-url': string),因此类与集合中已有的文档一致。
  • 每个文档中都有非空值的字段得到 required: true 和 @IsNotEmpty();其余字段只得到 @IsOptional()。输入中的 _id key 会被跳过,因为已经声明了 _id: MongooseSchema.Types.ObjectId。
  • 会生成 export type ProductDocument = Product & Document,用于 @InjectModel(Product.name) model: Model<ProductDocument> 这样的注入。

使用场景

给 NestJS 服务添加集合

把其他团队发来的事件 payload 或爬虫得到的 JSON 放进来,得到 schema 类,然后用 @InjectModel 注入,马上就能调用 create 或 find。

把 Express 的 Mongoose 模型迁到 NestJS

导出几份由旧的 new Schema({...}) 模型保存的文档,粘贴到这里,就能改写成基于装饰器的类,而不会在手动搬运字段时遗漏。

注意事项与限制

  • @IsNotEmpty() 和 @IsOptional() 位于 schema 类上,但 ValidationPipe 校验的是 controller 的 DTO。要校验请求,请把这些装饰器移到 DTO 类中,或新建一个 DTO。
  • @Schema() 没有选项,所以集合名遵循 Mongoose 的规则,把模型名转成小写复数:products。如果需要特定名称,请设置 @Schema({ collection: 'product' })。
  • 可选字段输出时仍不带 ?(例如 memo: string)。开启 strictNullChecks 时,改成 memo?: string 更安全。
  • 子文档以 Mixed 存储,而不是类型化的 schema。如果需要在其内部校验,请另外定义一个 @Schema() 类,并使用 @Prop({ type: SubSchema })。

常见问题

为什么用 & Document 而不是继承 Document?

这沿用了 NestJS 官方文档的默认写法:schema 类只作为普通的字段定义,ProductDocument 只在需要 save() 等 Mongoose 文档方法的地方使用。在 Mongoose 7+ 中,可以直接换成 HydratedDocument<Product>。

如果项目不使用 class-validator 怎么办?

删掉 import { IsNotEmpty, IsOptional } from 'class-validator' 这一行以及每个字段上的这两个装饰器。schema 的行为仅由 @Prop() 中的 required 控制。

@Prop() 中必须指定 type 吗?

开启 emitDecoratorMetadata 时,简单类型可以被推断,但数组以及 Date | null 这样的联合类型无法推断。生成的代码预先写明 type,这样以后修改属性的 TypeScript 类型时,行为也保持不变。