Understanding Virtuals In Mongoose

Mongoose is a popular Node.js library for working with MongoDB, a popular NoSQL database. One of the powerful features of Mongoose is the ability to define "virtuals" for your Mongoose models.

Virtuals in Mongoose are a way to create a field in a Mongoose model that can be manipulated like any other field, but that does not actually get persisted to the database. Instead, virtuals are calculated dynamically whenever the field is accessed. This can be useful for performing calculations on data stored in the database, or for creating fields that are derived from other fields but do not need to be stored separately.

To define a virtual property in Mongoose, you need to use the virtual method on your schema. For example, if you have a schema for a User model with a firstName and lastName field, you could define a virtual fullName property as follows,

const userSchema = new Schema({
    firstName: String,
    lastName: String
});
userSchema.virtual('fullName').get(function() {
    return `${this.firstName} ${this.lastName}`;
});

The get function defines the code that will be executed when you access the fullName property. In this case, it simply concatenates the firstName and lastName fields.

You can also define a set function for your virtual property, which will be called when you assign a value to the property. This can be useful if you want to update other fields in your document when the virtual property is set. For example,

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

With this code, you can now set the fullName property and have it automatically update the firstName and lastName fields,

const user = new User({
    firstName: 'John',
    lastName: 'Doe'
});
console.log(user.fullName); // "John Doe"
user.fullName = 'Jane Doe';
console.log(user.firstName); // "Jane"
console.log(user.lastName); // "Doe"

Virtuals are a very useful feature in Mongoose and can help you to simplify and streamline your code. They are also a good way to abstract away complex calculations or logic, making your code easier to read and understand.

I hope you found this article about Virtuals useful. In case you've any queries or feedback feel free to drop a comment.


Similar Articles