Getter and Setter with Mongoose Virtual Fields
Getter and Setter with Mongoose Virtual Fields
Mongoose Virtual Fields and getter/setter functions offer great convenience for Node.js developers working with MongoDB. In many software projects, there is a need for fields that are not physically stored in the database but need to be calculated dynamically. At this point, Mongoose's "virtual" feature comes into play and makes the software architecture both clean and flexible.
What are Mongoose Virtual Fields?
Mongoose Virtual Fields allow us to dynamically add data belonging to a document without actually saving it to the database. For example, it can be used to display a user's full name (by combining first and last names) without storing it. Mongoose Virtual Fields feature can be used with getter and setter. Thus, you can not only read but also set the data from outside in a special format.
How Do Getter and Setter Functions Work?
The getter function is used to calculate and return the value of the virtual field. The setter function is used to automatically distribute data to the relevant physical fields when a value is assigned to this field from outside. This method helps you manage data in your models created with Mongoose more flexibly.
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
ad: String,
soyad: String
});
// Define virtual field
userSchema.virtual('tamAd')
.get(function () {
return `${this.ad} ${this.soyad}`;
})
.set(function (value) {
const parts = value.split(' ');
this.ad = parts[0];
this.soyad = parts.slice(1).join(' ');
});
const User = mongoose.model('User', userSchema);
// Example usage
yeniKullanici = new User();
yeniKullanici.tamAd = 'Ali Veli';
console.log(yeniKullanici.ad); // Ali
console.log(yeniKullanici.soyad); // Veli
console.log(yeniKullanici.tamAd); // Ali Veli
Advantages of Using Virtual Fields
With Mongoose Virtual Fields and getter/setter functions, your code:
- Becomes more readable and maintainable.
- You can keep complex calculations in the model layer.
- Increases data consistency; for example, separation of names makes update operations easier.
Conclusion
Using getter and setter functions with Mongoose Virtual Fields in Node.js and Mongoose-powered applications adds cleanliness, flexibility, and sustainability to your projects. Thanks to virtual fields, you can extend your model structure and develop modern applications. Especially in complex data relations, it ensures the software architecture remains simple and enables more efficient data management.

Yorum Gönder