執行我用貓鼬對我的數據訪問層,我真的很喜歡不同 功能它提供了創建文檔模型(屬性,方法,靜態方法..)貓鼬和懶惰初始化屬性在正確的範圍
我使用mongoose的虛擬屬性功能來創建不會保留到MongoDB的屬性。然而,這些屬性是計算昂貴(並多次使用它們不幫助我)。
讓我們例如在mongoose virtual 它堅持person.name.first
和person.name.last
同樣的例子,並使用虛擬屬性的person.name.full
比方說,我想計算每文檔的壽命person.name.full只有一次
(如果我允許設置屬性或它的依賴字段就像在這個例子中那樣,那麼對於每一個髒集合也是如此)。
我需要在受案範圍的額外的變量,所以很自然我用瓶蓋這個 但「這個」範圍在計算該屬性的功能,是全球的對象,而不是的我正在處理的文件。
代碼:
var makeLazyAttribute = function(computeAttribute) {
var attribute = null;
return function() {
if(!attribute) {
attribute = computeAttribute();
}
return attribute;
}
};
MySchema.virtual('myAttribute').get(makeLazyAttribute(function() {
// some code that uses this, this should be the document I'm working on
// error: first is not defined, inspecting what is this gives me the global object
return this.first + this.last
}));
請幫幫忙!