2012-05-18 58 views
0

執行我用貓鼬對我的數據訪問層,我真的很喜歡不同 功能它提供了創建文檔模型(屬性,方法,靜態方法..)貓鼬和懶惰初始化屬性在正確的範圍

我使用mongoose的虛擬屬性功能來創建不會保留到MongoDB的屬性。然而,這些屬性是計算昂貴(並多次使用它們不幫助我)。
讓我們例如在mongoose virtual 它堅持person.name.firstperson.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 

})); 

請幫幫忙!

回答

0

好了,好了,我已經取得了一些進展makeLazyAttribute在受案範圍 所以我只需要改變attribute = computeAttribute();
attribute = computeAttribute.call(this);不執行。

但是,現在我只記得第一個computeAttribute()調用,而不是記住 每個文檔的第一個函數調用。 必須有一種方法來緩解這一點。