Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Virtuals and Getters | Advanced Mongoose Features
MongoDB and Mongoose Essentials

Virtuals and Getters

Pyyhkäise näyttääksesi valikon

In many applications, you may want to present data that is derived from existing fields in your documents, without actually storing that computed data in the database. Mongoose provides a feature called virtual properties (or simply "virtuals") that allows you to define computed fields on your schema. These virtuals are not persisted to the database, but you can access them like any other property when you retrieve your documents.

Here is a code example demonstrating how to define a virtual property called fullName in a User schema. This virtual combines the user's firstName and lastName into a single string:

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  firstName: String,
  lastName: String,
  email: String
});

// Define a virtual property 'fullName'
userSchema.virtual("fullName").get(function () {
  // 'this' refers to the document instance
  return `${this.firstName} ${this.lastName}`;
});

const User = mongoose.model("User", userSchema);

// Example usage:
const user = new User({
  firstName: "Jane",
  lastName: "Doe",
  email: "jane@example.com"
});
console.log(user.fullName); // Output: 'Jane Doe'

In this example, the fullName virtual is defined using the .virtual() method on the schema, followed by a .get() function. Whenever you access user.fullName, Mongoose will call this getter and return the combined name. Notice that fullName is not saved in the database; it is computed each time you access it on a document instance.

How virtuals work and when to use them

Virtuals in Mongoose are properties that you define on your schema, but which are not actually stored in MongoDB. Instead, they are computed dynamically using getter functions. When you retrieve a document from the database, you can access these virtuals as if they were real properties. In the code example above, the fullName virtual concatenates the firstName and lastName fields. This is useful when you want to display or use a value that depends on other fields but do not want to duplicate data or store unnecessary information.

Use virtuals when you need:

  • To combine or transform existing document fields for presentation or logic;
  • To provide computed values that depend on one or more document properties;
  • To avoid storing redundant or unnecessary data in your MongoDB collections.

Virtuals are especially handy for formatting, creating derived fields, or representing relationships (such as a user's profile URL based on their ID). Remember that since virtuals are not persisted, you cannot query or filter documents by virtual properties at the database level—they exist only on the Mongoose document instance after retrieval or creation.

question mark

Which statement about Mongoose virtual properties is correct?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 4. Luku 3

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 4. Luku 3
some-alt