Skip to content

Commit 3ac0ce6

Browse files
docs: add docs on the virtual decorator (mongoose)
1 parent 359c845 commit 3ac0ce6

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

content/techniques/mongo.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,31 @@ export type PersonDocumentOverride = {
649649
export type PersonDocument = HydratedDocument<Person, PersonDocumentOverride>;
650650
```
651651

652+
#### Virtuals
653+
654+
In Mongoose, a **virtual** is a property that exists on a document but is not persisted to MongoDB. It is not stored in the database but is computed dynamically whenever it's accessed. Virtuals are typically used for derived or computed values, like combining fields (e.g., creating a `fullName` property by concatenating `firstName` and `lastName`), or for creating properties that rely on existing data in the document.
655+
656+
```ts
657+
class Person {
658+
@Prop()
659+
firstName: string;
660+
661+
@Prop()
662+
lastName: string;
663+
664+
@Virtual({
665+
get: function () {
666+
return `${this.firstName} ${this.lastName}`;
667+
},
668+
})
669+
fullName: string;
670+
}
671+
```
672+
673+
> info **Hint** The `@Virtual()` decorator is imported from the `@nestjs/mongoose` package.
674+
675+
In this example, the `fullName` virtual is derived from `firstName` and `lastName`. Even though it behaves like a normal property when accessed, it’s never saved to the MongoDB document.:
676+
652677
#### Example
653678

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

0 commit comments

Comments
 (0)