What is mongoose’s Virtual?

  mongodb, question

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

This sentence is not very clear. Please don’t translate. I hope I can explain it in my own words. Examples are better. Thank you

You can use mongoose to add and set virtual attributes, but the value of this virtual attribute will not be saved in the database.
For example, a parameter name passed from the foreground to the background represents the user’s name, but the database stores two fields, the last name and the first name, which can use virtual attributes.

//Format of cache in database
 var schema = new Schema({
 name: {
 first: { 'type': String },
 last: { 'type': String },
 }
 });
 
 //when obtaining the fullname attribute of the schema, concatenate name.first and name.last in the schema to return
 var virtual = schema.virtual('fullname');
 virtual.get(function () {
 return this.name.first + ' ' + this.name.last;
 });
 //when setting the fullname attribute of the schema, the set words are separated by spaces and assigned to the name.first and name.last attributes in the schema respectively
 var virtual = schema.virtual('fullname');
 virtual.set(function (v) {
 var parts = v.split(' ');
 this.name.first = parts[0];
 this.name.last = parts[1];
 });
 
 //when saving the schema to the database, only name.first and name.last will be saved
 //The value of the fullname attribute is not saved to the database, which is virtual

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

The parameter v of function in set is the value when the virtual attribute is set. it is not stored in the database, but it also has significance. for example, as in the example, it has only one first name in the user’s view, but in the database, the last name and the first name are stored, because they are divided into the last name and the first name, so we can make statistics on the user and how many people have the last name Zhang.

For another example, the status of the order is 0,1,2,3,4,5,6,7 stored in the database. However, on the page, it shows unpaid, paid, to be shipped, shipped, to be received, completed, to be evaluated, etc. We can set a virtual attribute

var virtual = schema.virtual('statusName');
 virtual.get(function () {
 switch(this.status){
 Case 0: return' to be shipped';
 Case 1: return' to be harvested';
 Case 2: return' Completed';
 Default: return' to be paid';
 }
 return this.name.first + ' ' + this.name.last;
 });