虚拟化与Mongoose中的方法

我明白, static方法是Class Methods ,该methodsInstance MethodsVirtuals也像Instance Methods但它们不存储在数据库中。

但是,我想知道这是否是methodsvirtuals之间的唯一区别。 还有什么我失踪?

实例方法,静态方法或虚拟方法都不存储在数据库中。 方法和虚拟之间的区别在于,虚拟像属性一样被访问,方法被称为函数。 在实例/静态和虚拟之间没有区别,因为在类上可以访问虚拟静态属性是没有意义的,但是在类上有一些静态实用工具或工厂方法是有意义的。

 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); // would print "Alex Ford" to the console 

而方法被称为正常function。

 PersonSchema.method('fullName', function () { return this.name.first + ' ' + this.name.last; }); var person = new Person({ name: { first: 'Alex', last: 'Ford' } }); console.log(person.fullName()); // notice this time you call fullName like a function 

您也可以像设置常规属性一样“设置”虚拟属性。 只需调用.get.set来设置两个操作的function。 注意.get你返回一个值,而在.set你接受一个值,并用它来设置文档上的非虚拟属性。

 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); // would log out "Alex" person.name.full = 'Billy Bob'; // would set person.name.first and person.name.last appropriately console.log(person.name.first); // would log out "Billy" 

你可以在技术上使用一切方法,而不使用虚拟属性,但是虚拟属性对于某些东西比较优雅,比如我在这里用person.name.full显示的例子。