What is the Virtual of mongoose?

Virtual properties are document properties that you can get and set but that do not get persisted to MongoDB.

I don"t quite understand this sentence. Please do not translate. I hope you can explain it in your own words. It is better to have examples. Thank you

Feb.26,2021

roughly means that you can use mongoose to add and set virtual properties, but the value of this virtual property is not saved to the database.
for example, a parameter name, is passed from the foreground to the background to represent the user's name, but the database stores two fields, the last name and the first name, so you can use the virtual attribute

// 
var schema = new Schema({
    name: {
        first: { 'type': String },  
        last: { 'type': String },
      }
});

//  schema fullname, schema  name.first  name.last 
var virtual = schema.virtual('fullname');
virtual.get(function () {
  return this.name.first + ' ' + this.name.last;
});
// schema fullname ,, schema  name.first  name.last 
var virtual = schema.virtual('fullname');
virtual.set(function (v) {
  var parts = v.split(' ');
  this.name.first = parts[0];
  this.name.last = parts[1];
});

//  schema , name.first  name.last
// fullname,virtual

http://mongoosejs.com/docs/ap.

The parameter v of function in

set is the value when setting the virtual property. It is not saved to the database, but it also has the meaning of existence. For example, as in the example, from the user's point of view, it has only one name, but in the database, it is necessary to save the surname and first name, because it is divided into surname and first name. We can follow up to count the number of people surnamed Zhang. This is just an example.

for example, for the status of the order, what is stored in the database is 0Personl, 2pyrmology, 3pjin4, 5jin7. But on the page, it shows unpaid, paid, ready for delivery, delivered, received, completed, evaluated, etc. We can set a virtual property

var virtual = schema.virtual('statusName');
virtual.get(function () {
  switch(this.status){
     case 0: return '';
     case 1: return '';
     case 2: return '';
     default: return '';
  }
  return this.name.first + ' ' + this.name.last;
});
Menu