我理解static方法是Class Methods,methods是Instance Methods,Virtuals也像Instance Methods,但它们没有存储在数据库中。
但是,我想知道这是否是methods和virtuals之间唯一的区别。还有什么是我遗漏的吗?
发布于 2015-04-16 17:27:00
实例方法、静态方法或虚拟化都不存储在数据库中。方法和虚拟人之间的区别在于,虚拟者被像属性一样地访问,方法被称为类似函数。实例/静态与虚拟没有区别,因为在类上访问虚拟静态属性是没有意义的,但是在类上有一些静态实用程序或工厂方法是有意义的。
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 appropriately
console.log(person.name.first);
// would log out "Billy"从技术上讲,您可以对所有东西使用方法,而从不使用虚拟属性,但是对于某些事情来说,虚拟属性是很优雅的,比如我在这里展示的关于person.name.full的例子。
发布于 2019-07-03 03:50:10
我试图找出何时使用虚拟程序以及何时使用实例,并将其总结如下:
Static-用于不需要运行模型实例的方法(操作)。或者,针对模型的通用操作。
找到一份文件,列出所有的文件。
实例-用于确实需要模型实例的方法(操作)。
例如,根据当前实例数据查找或检索数据。与与实例关联的其他文档一样。model.getRelatedDocs()
虚拟-用于读取模型的属性,并在代码级别表明这些属性是属性/属性而不是方法。另外,对于基于已经加载到实例中的数据的组合属性。例如,胰脏的全名例子。
https://stackoverflow.com/questions/29681715
复制相似问题