6
我明白static
方法是Class Methods
,那methods
是Instance Methods
和Virtuals
也都是Instance Methods
但它們不是存儲在數據庫中。VIRTUALS VS方法在貓鼬
但是,我想知道這是否是methods
和virtuals
之間的唯一區別。還有什麼我失蹤的?
我明白static
方法是Class Methods
,那methods
是Instance Methods
和Virtuals
也都是Instance Methods
但它們不是存儲在數據庫中。VIRTUALS VS方法在貓鼬
但是,我想知道這是否是methods
和virtuals
之間的唯一區別。還有什麼我失蹤的?
實例方法,靜態方法或虛擬方法都不存儲在數據庫中。方法和虛擬之間的區別在於虛擬像屬性一樣被訪問,而方法被稱爲函數。在實例/靜態和虛擬之間沒有區別,因爲在類上可以訪問虛擬靜態屬性是沒有意義的,但是在類上有一些靜態實用工具或工廠方法是有意義的。
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
的例子。