Neither instance methods, nor static methods, nor virtual files are stored in the database. The difference between methods and virtual parts is that virtual objects are treated as properties, and methods are called similar functions. There is no difference between a / static instance and a virtual one, because it makes no sense to have a virtual static property available in the class, but it makes sense to have some static utilities or factory methods in the class.
var PersonSchema = new Schema({ name: { first: String, last: String } }); PersonSchema.virtual('name.full').get(function () { return this.name.first + ' ' + this.name.last; }); var Person = mongoose.model('Person', PersonSchema); var person = new Person({ name: { first: 'Alex', last: 'Ford' } }); console.log(person.name.full);
While methods are called as ordinary functions.
PersonSchema.method('fullName', function () { return this.name.first + ' ' + this.name.last; }); var person = new Person({ name: { first: 'Alex', last: 'Ford' } }); console.log(person.fullName());
You can also “set” virtual properties, for example, with ordinary properties. Just call .get and .set to configure the functionality of both actions. Note that in .get you return a value, while in .set you accept a value and use it to set non-virtual properties in your document.
PersonSchema .virtual('name.full') .get(function () { return this.name.first + ' ' + this.name.last; }) .set(function (fullName) { var parts = fullName.split(' '); this.name.first = parts[0]; this.name.last = parts[1]; }); var person = new Person({ name: { first: 'Alex', last: 'Ford' } }); console.log(person.name.first);
You can technically use methods for everything and never use virtual properties, but virtual properties are elegant for certain things, such as the examples I showed here with person.name.full .
source share