Using MongoDB Virtuals to Create Computed Properties in Your Schema

Using MongoDB Virtuals to Create Computed Properties in Your Schema

MongoDB is a powerful NoSQL database that offers many features to make working with data easier and more efficient. One of these features is virtuals, which allow you to define computed properties on your documents. In this blog post, we'll explore the concept of virtuals in MongoDB and how you can use them to enhance your data model.

What are MongoDB Virtuals?

MongoDB virtuals are properties that do not persist in the database but can be accessed as if they were real properties on the document. They are computed properties that are created by combining other properties on the document or by performing some kind of computation. Virtuals are useful when you want to include data in your response that is not stored in the database or when you want to modify existing data before returning it.

Creating Virtuals in Your Schema

To create virtuals in your MongoDB schema, you need to define them using the virtual() function on your schema object. The virtual() function takes two arguments: the name of the virtual property and an object that defines the getter and/or setter functions for the property. Here's an example:

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

userSchema.virtual('fullName').get(function () {
  return `${this.firstName} ${this.lastName}`;
});

In this example, we've defined a virtual property called "fullName" that is computed by combining the "firstName" and "lastName" properties. The getter function for the virtual property returns the computed value.

Accessing Virtuals in Your Documents

To access virtuals in your documents, you simply access them as if they were real properties on the document. Here's an example:

const user = new User({
  firstName: 'John',
  lastName: 'Doe',
});

console.log(user.fullName); // "John Doe"

In this example, we've created a new user document and accessed the "fullName" virtual property. MongoDB will compute the value of the virtual property using the getter function defined in the schema and return the computed value.

Virtuals with Setters

Virtuals can also have setter functions, which allow you to modify the value of the virtual property before it is saved to the database. Here's an example:

userSchema.virtual('fullName').get(function () {
  return `${this.firstName} ${this.lastName}`;
}).set(function (value) {
  const parts = value.split(' ');
  this.firstName = parts[0];
  this.lastName = parts[1];
});

const user = new User({
  fullName: 'John Doe',
});

console.log(user.firstName); // "John"
console.log(user.lastName); // "Doe"

In this example, we've defined a setter function for the "fullName" virtual property that splits the value into its parts and assigns them to the "firstName" and "lastName" properties on the document. When we create a new user document with the "fullName" property set to "John Doe", MongoDB will use the setter function to split the value and assign the parts to the "firstName" and "lastName" properties.

Conclusion

MongoDB virtuals are a powerful feature that allows you to define computed properties on your documents. They are useful when you want to include data in your response that is not stored in the database or when you want to modify existing data before returning it. In this blog post, we've explored how to create virtuals in your schema and how to access them in your documents. With virtuals, you can create more flexible and efficient data models in MongoDB.