把 JSON 转换成 NestJS @nestjs/mongoose 的 schema 类:一个每个字段都带 @Prop() 的 @Schema() 类、用 SchemaFactory.createForClass() 构建的 schema,以及 ProductDocument 类型,全部放在一个文件里。每个字段还带有 class-validator 的 @IsNotEmpty() 或 @IsOptional()。
当 NestJS 模块需要一个 schema 来注册到 MongooseModule.forFeature(),手头已经有要存储的文档示例,而逐个手写装饰器又太慢时,就可以用它。
模型名 中输入类名(默认 MyModel)。输入 product 会生成 Product、ProductDocument 和 ProductSchema。product.schema.ts,并用 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);示例是单个、字段齐全的文档,所以每个字段都得到 required: true 和 @IsNotEmpty()。restocked_at 是日期格式的字符串,因此类型为 Date,属性保留存储时的 key 名 restocked_at。
@Prop({ type: MongooseSchema.Types.String, required: true })。Mongoose 的 Schema 以 MongooseSchema 的名义导入,以免与 Schema 装饰器冲突。number、boolean,ISO 8601 日期字符串为 Date,其他一律为 string,包括 "0042" 这样的纯数字字符串。MongooseSchema.Types.Mixed 声明,类型为 Record<string, unknown>;单一基本类型的数组变成 [MongooseSchema.Types.String] 配合 string[] 这样的形式。'home-url': string),因此类与集合中已有的文档一致。required: true 和 @IsNotEmpty();其余字段只得到 @IsOptional()。输入中的 _id key 会被跳过,因为已经声明了 _id: MongooseSchema.Types.ObjectId。export type ProductDocument = Product & Document,用于 @InjectModel(Product.name) model: Model<ProductDocument> 这样的注入。把其他团队发来的事件 payload 或爬虫得到的 JSON 放进来,得到 schema 类,然后用 @InjectModel 注入,马上就能调用 create 或 find。
导出几份由旧的 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>。
删掉 import { IsNotEmpty, IsOptional } from 'class-validator' 这一行以及每个字段上的这两个装饰器。schema 的行为仅由 @Prop() 中的 required 控制。
@Prop() 中必须指定 type 吗?开启 emitDecoratorMetadata 时,简单类型可以被推断,但数组以及 Date | null 这样的联合类型无法推断。生成的代码预先写明 type,这样以后修改属性的 TypeScript 类型时,行为也保持不变。