From 3ac0ce63a3082c4a6b7b2c77388cec9ab5ce938a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20My=C5=9Bliwiec?= Date: Mon, 21 Oct 2024 13:59:34 +0200 Subject: [PATCH] docs: add docs on the virtual decorator (mongoose) --- content/techniques/mongo.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/content/techniques/mongo.md b/content/techniques/mongo.md index 5657a25815..4abaaf167b 100644 --- a/content/techniques/mongo.md +++ b/content/techniques/mongo.md @@ -649,6 +649,31 @@ export type PersonDocumentOverride = { export type PersonDocument = HydratedDocument; ``` +#### Virtuals + +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. + +```ts +class Person { + @Prop() + firstName: string; + + @Prop() + lastName: string; + + @Virtual({ + get: function () { + return `${this.firstName} ${this.lastName}`; + }, + }) + fullName: string; +} +``` + +> info **Hint** The `@Virtual()` decorator is imported from the `@nestjs/mongoose` package. + +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.: + #### Example A working example is available [here](https://github.com/nestjs/nest/tree/master/sample/06-mongoose).