File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change @@ -527,6 +527,74 @@ MongooseModule.forRootAsync({
527527});
528528```
529529
530+ #### Subdocuments and subdocument arrays
531+
532+ If you want to nest subdocuments within a parent document you can define your schema as shown below:
533+
534+ ``` typescript
535+ @Schema
536+ class Name {
537+ @Prop ()
538+ firstName: string ;
539+
540+ @Prop ()
541+ lastName: string ;
542+ }
543+
544+ const NameSchema = SchemaFactory .createForClass (Name );
545+
546+ @Schema ()
547+ class Person {
548+
549+ @Prop (NameSchema )
550+ name: Name ;
551+ }
552+
553+ const PersonSchema = SchemaFactory .createForClass (Person );
554+
555+ type PersonDocumentOverride = {
556+ name: Types .Subdocument <Types .ObjectId & Name >;
557+ }
558+
559+ type PersonDocument = HydratedDocument <
560+ Person ,
561+ PersonDocumentOverride
562+ >;
563+ ```
564+
565+ If you want to have multiple documents you can use a subdocuments array. Important is to override the type of the property.
566+
567+ ``` typescript
568+ @Schema
569+ class Name {
570+ @Prop ()
571+ firstName: string ;
572+
573+ @Prop ()
574+ lastName: string ;
575+ }
576+
577+ const NameSchema = SchemaFactory .createForClass (Name );
578+
579+ @Schema ()
580+ class Person {
581+
582+ @Prop ([NameSchema ])
583+ name: Name [];
584+ }
585+
586+ const PersonSchema = SchemaFactory .createForClass (Person );
587+
588+ type PersonDocumentOverride = {
589+ name: Types .DocumentArray <Name >;
590+ }
591+
592+ type PersonDocument = HydratedDocument <
593+ Person ,
594+ PersonDocumentOverride
595+ >;
596+ ```
597+
530598#### Example
531599
532600A 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