📜  mongoose virtual (1)

📅  最后修改于: 2023-12-03 15:32:57.602000             🧑  作者: Mango

Mongoose Virtual

Mongoose Virtuals are a powerful feature that allows you to define properties on your MongoDB documents that don't have to be saved to the database. These virtual properties can be used in your application code just like any other regular properties, but they won't be persisted to the database.

What is a Virtual?

A virtual is a property that is not stored in MongoDB but computed dynamically. In other words, it is a property that doesn't exist on the document object itself, but can be accessed as if it does. A Virtual intercepts calls made to a model getter/setter and are defined as part of the schema.

To define a virtual field in Mongoose, you need to use the virtual() method. Here's a simple example:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  firstName: String,
  lastName: String
});

UserSchema.virtual('fullName').get(function() {
  if (this.firstName && this.lastName) {
    return this.firstName + ' ' + this.lastName;
  }
  return '';
});

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

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

In this example, we're defining a virtual field called fullName that concatenates the firstName and lastName fields on the User model. The get() function is where we define the computation that needs to be performed to get the value of the virtual field.

The benefit of using virtuals

The benefit of using virtuals is that it allows you to define properties on the fly without storing them to MongoDB. Since virtuals do not have any persistent storage, they are more lightweight than regular fields. When you want to retrieve the virtual field from the model, the computation is performed and the value is returned.

There are many use cases for virtuals. For example, you may want to calculate the age of a person based on their date of birth, or you might want to concatenate two or more fields together to form a single field. In both of these cases, you could define a virtual field to achieve the desired output.

Overall, virtuals are an efficient way to define computed properties on your MongoDB documents. They are lightweight, easy to use, and provide a lot of flexibility in how you structure your data.