File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change @@ -593,6 +593,62 @@ MongooseModule.forRootAsync({
593593
594594This provides a flexible way to manage connection events, enabling you to handle changes in connection status effectively.
595595
596+ #### Subdocuments
597+
598+ To nest subdocuments within a parent document, you can define your schemas as follows:
599+
600+ ``` typescript
601+ @@filename (name .schema )
602+ @Schema ()
603+ export class Name {
604+ @Prop ()
605+ firstName: string ;
606+
607+ @Prop ()
608+ lastName: string ;
609+ }
610+
611+ export const NameSchema = SchemaFactory .createForClass (Name );
612+ ```
613+
614+ And then reference the subdocument in the parent schema:
615+
616+ ``` typescript
617+ @@filename (person .schema )
618+ @Schema ()
619+ export class Person {
620+ @Prop (NameSchema )
621+ name: Name ;
622+ }
623+
624+ export const PersonSchema = SchemaFactory .createForClass (Person );
625+
626+ export type PersonDocumentOverride = {
627+ name: Types .Subdocument <Types .ObjectId & Name >;
628+ };
629+
630+ export type PersonDocument = HydratedDocument <Person , PersonDocumentOverride >;
631+ ```
632+
633+ If you want to include multiple subdocuments, you can use an array of subdocuments. It's important to override the type of the property accordingly:
634+
635+ ``` typescript
636+ @@filename (name .schema )
637+ @Schema ()
638+ export class Person {
639+ @Prop ([NameSchema ])
640+ name: Name [];
641+ }
642+
643+ export const PersonSchema = SchemaFactory .createForClass (Person );
644+
645+ export type PersonDocumentOverride = {
646+ name: Types .DocumentArray <Name >;
647+ };
648+
649+ export type PersonDocument = HydratedDocument <Person , PersonDocumentOverride >;
650+ ```
651+
596652#### Example
597653
598654A working example is available [ here] ( https://github.com/nestjs/nest/tree/master/sample/06-mongoose ) .
You can’t perform that action at this time.
0 commit comments