NestJS-如何使用装饰符创建嵌套架构 [英] NestJS - How to create nested schema with decorators

查看:25
本文介绍了NestJS-如何使用装饰符创建嵌套架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想用mongoose构建以下架构:

const userSchema = new Schema({
  name: {
    firstName: String,
    lastName: String
  }
})

如何使用NestJS装饰器(@Schema()&;@Prop())?

我尝试了此方法,但没有成功:

@Schema()
class Name {
  @Prop()
  firstName: string;

  @Prop()
  lastName: string;
}

@Schema()
class User extends Document {
  @Prop({ type: Name })
  name: Name;
}

我也不想使用raw()方法。

推荐答案

我的方法非常有效,不涉及删除@Schema()

// Nested Schema
@Schema()
export class BodyApi extends Document {
  @Prop({ required: true })
  type: string;

  @Prop()
  content: string;
}
export const BodySchema = SchemaFactory.createForClass(BodyApi);

// Parent Schema
@Schema()
export class ChaptersApi extends Document {
  // Array example
  @Prop({ type: [BodySchema], default: [] })
  body: BodyContentInterface[];

  // Single example
  @Prop({ type: BodySchema })
  body: BodyContentInterface;
}
export const ChaptersSchema = SchemaFactory.createForClass(ChaptersApi);

当您在架构上设置了该选项时,这将正确保存并显示时间戳

这篇关于NestJS-如何使用装饰符创建嵌套架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆