Skip to content

Commit a9cbb00

Browse files
Merge branch 'gerritlo-feature/mongoose-subdocuments'
2 parents 996461a + 33115f8 commit a9cbb00

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

content/techniques/mongo.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -593,6 +593,62 @@ MongooseModule.forRootAsync({
593593

594594
This 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

598654
A working example is available [here](https://github.com/nestjs/nest/tree/master/sample/06-mongoose).

0 commit comments

Comments
 (0)