In Mongoose, automatically calculated properties are typically implemented using virtual properties (Virtuals). Virtual properties are not part of the database model; they exist only at the logical layer, meaning they are not stored directly in the database. Virtual properties are ideal for scenarios where you want to derive values from existing database fields.
For example, consider a user model that includes each user's first and last name, and we want to create a virtual property to automatically calculate the user's full name.
Here is an example of how to define this virtual property:
javascriptconst mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true } }); // Define a virtual property `fullName` userSchema.virtual('fullName').get(function () { return `${this.firstName} ${this.lastName}`; }); // Create the model const User = mongoose.model('User', userSchema); // Use the model const user = new User({ firstName: 'Li', lastName: 'Lei' }); console.log(user.fullName); // Output: "Li Lei"
In this case, fullName is derived by concatenating the firstName and lastName fields. When you access user.fullName, it automatically executes the defined getter function and returns the calculated full name.
Virtual properties can be flexibly used in various scenarios, such as calculating age, full name, or formatting addresses. Importantly, since they do not consume database storage space, they can improve the efficiency and flexibility of data processing.