mongoose 嵌套对象的模式装饰器有什么用

bsxbgnwa  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(117)

我目前正在学习NestJS和Mongoose。在寻找我的另一个问题的答案时,我想出了这篇文章How to write down nested schemas for mongoose using NestJS nomenclature
在答案中,它包含以下代码:

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

export type CatDocument = Cat & Document;

@Schema()
export class Owners {
  @Prop()
  names: [string];
}

@Schema()
export class Cat {
  @Prop()
  name: string;

  @Prop()
  age: number;

  @Prop()
  breed: string;

  @Prop()
  owners: Owners;//schema for owner
}

export const CatSchema = SchemaFactory.createForClass(Cat);

根据我的理解,如果我们不对创建的模式(上面例子中的Owners)使用SchemaFactory.createForClass()函数,NestJS就不会为我们生成Mongoose模式。
所以我想知道在上面的代码中模式装饰器的用途是什么?

export class Owners {
    names: [string];
}

然后像这样在Cat类中定义它

@Prop(type: Owners)
owners: Owners;
voase2hg

voase2hg1#

您可能应该查看https://mongoosejs.com/docs/subdocs.html#subdocuments-versus-nested-paths,因为这正是您提供的两个示例之间的区别。
但是,您还应该阅读有关子文档确切含义的部分:
子文档类似于普通文档。嵌套架构可以具有中间件、自定义验证逻辑、虚拟和顶级架构可以使用的任何其他功能。主要区别在于子文档不是单独保存的,而是在保存其顶级父文档时保存。
因此,如果您希望使用中间件或自定义验证之类的工具,您一定要使用嵌套文档(使用模式装饰器)。

相关问题