首页 > 解决方案 > NestJs with Mongoose 如何使用类、@Schem() 和 @Prop() 装饰器构建基本实体/模式

问题描述

我想构建一个基本模式并在以后扩展它,以便不必在新模型中定义相同的属性。我当前如何定义架构的示例:

import { Schema, SchemaFactory, Prop } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type BtcDocument = BtcEntity & Document;

@Schema({ timestamps: true, collection: 'btc' })
export class BtcEntity {
   @Prop()
   currency: string;

   @Prop({
      unique: true,
   })
   address: string;
   
   /**
   .
   . other props
   .
   */
}

export const BtcSchema = SchemaFactory.createForClass(BtcEntity);

我想做如下的事情

@Schema({ timestamps: true })
export class WalletBaseSchema {
   @Prop()
   currency: Currency;

   @Prop({
      unique: true,
   })
   address: string;
   
   /**
   .
   . other props
   .
   */
}

export WalletBaseEntity;

然后将此具有自定义值的基本实体扩展到父属性。例子:

export type LtcDocument = LtcEntity & Document;

@Schema({ timestamps: true, collection: 'ltc' })
export class LtcEntity extends WalletBaseSchema {
   /**
   .
   . all parent props will be applied here somehow
   .
   */
   @Prop({ default: Currency.LTC })
   currency: Currency
}

export const LtcSchema = SchemaFactory.createForClass(LtcEntity);

谢谢。

标签: classinheritancemongooseconstructornestjs

解决方案


推荐阅读