实例方法,静态方法或虚拟方法均未存储在数据库中。方法与虚拟函数之间的区别在于,虚拟函数的访问方式类似于属性,方法的调用方式类似于函数。实例与静态实例与虚拟实例之间没有区别,因为在类上具有可访问的虚拟静态属性是没有意义的,但在类上具有某些静态实用程序或工厂方法确实是有道理的。
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而方法的调用方式就像普通函数一样。
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设置两个操作的功能。注意,在中
.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 appropriatelyconsole.log(person.name.first);// would log out "Billy"从技术上讲,您可以对所有方法使用方法,而从不使用虚拟属性,但是对于某些事情(例如我在此处展示的示例)来说,虚拟属性很优雅
person.name.full。



