2

I'm currently learning NestJS and Mongoose. While looking for the answer to my other question, I've came up with this post How to write down nested schemas for mongoose using NestJS nomenclature

So in the answer, it has the following piece of codes:

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);

From my understanding, if we don't use SchemaFactory.createForClass() function for the created schema (Owners in the above example), NestJS won't generate a Mongoose Schema for us.

So I want to know what's the use of the Schema decorator in the above code? Should we just write something like this

export class Owners {
    names: [string];
}

And then define it in the Cat class like this

@Prop(type: Owners)
owners: Owners;
Tri Nong
  • 31
  • 1
  • 3

1 Answers1

1

You should probably take a look at https://mongoosejs.com/docs/subdocs.html#subdocuments-versus-nested-paths, since this is exactly the difference between both examples provided by you.

But additionally you should read the part on what subdocuments are exactly:

Subdocuments are similar to normal documents. Nested schemas can have middleware, custom validation logic, virtuals, and any other feature top-level schemas can use. The major difference is that subdocuments are not saved individually, they are saved whenever their top-level parent document is saved.

So if you want to use stuff like middleware or custom validation, you should definitely use nested documents (using schema decorator).

Fabian Strathaus
  • 3,192
  • 1
  • 4
  • 26
  • Hi, thanks for answering my question! However, what I really want to know is why do we use Schema decorator if SchemaFactory.createForClass() is not called. The above code looks confusing to me. If you have a look at this answer (https://stackoverflow.com/a/62714058), a subdocument is created when you create a schema with SchemaFactory.createForClass. And if I want a nested object (not subdocument), I could have just define it without the Schema decorator. – Tri Nong Oct 06 '22 at 17:43
  • Well, if you want to know why `SchemaFactory.createForClass()` has to be called only in parent schema and not in child schema your link does also give the answer. Because mongoose will call it itself once it iterators over the object properties (see the definition of `inspectTypeDefinition`. – Fabian Strathaus Oct 07 '22 at 05:55