2014-03-05 29 views
0

我是一種新的node.js和風帆,但它很容易,所以我喜歡它:) 我正在與風帆框架0.10rc3與MongoDB ans sails-mongo實際工作。我知道水線的貢獻者並不是mongodb(https://github.com/balderdashy/sails-mongo/issues/44#issuecomment-35561040)模型中嵌入文檔的主要粉絲,但無論如何,我想知道'this'變量是如何工作的,以及如何檢索當前元素內部陣列。嵌入式文檔中模型的'this'變量如何?

這裏是模型的爲例(我們可以稱之爲ProjetSpan):

module.exports = { 

attributes: { 

     proj: 
     { 
      model:'Projet' 
     }, 

     spans: 
     { 
      start: 
      { 
       type: 'DATETIME', 
       required: true, 
       datetime: true, 
       before: function() { 
        if (this.end < this.proj.end) 
         return this.end; 
        else 
         return this.proj.end; 
       } 
      }, 

      end: 
      { 
       type: 'DATETIME', 
       required: true, 
       datetime: true, 
       after: function() { 
        if (this.start > this.proj.start) 
         return this.start; 
        else 
         return this.proj.start; 
       } 
      } 
     } 
} 

}; 

如何「這個」會在這種情況下工作嗎?是'這'一個跨度(所以this.end將工作,而不是this.proj.end)或是'這'是一個ProjetSpan(所以this.proj.end工作,但不是this.end)?

最後,如何使this.end(當前範圍中的變量)和this.proj.end(當前文檔關聯中的變量)在此嵌入式上下文中工作?

回答

1

水線根本不支持嵌入式文檔,除了提供json數據類型。所以,你的典範不會帆工作,將需要改寫爲這樣的:

module.exports = { 

    attributes: { 

    proj: { 
     model:'projet' 
    }, 

    spans: { 
     type: 'json' 
    }, 

    before: function() { 

     if (this.spans.end < this.proj.end) { 
      return this.spans.end; 
     } else { 
      return this.proj.end; 
     } 

    }, 

    after: function() { 

     if (this.spans.start > this.proj.start) { 
      return this.spans.start; 
     } else { 
      return this.proj.start; 
     } 

    } 



} 

在實例方法(如beforeafter這裏),this指整個實例對象。您需要檢查以確保this.proj是一個對象(即它已填充了ProjetSpan.find({}).populate('project')),並且該this.spans.endthis.spans.start實際上存在(因爲Waterline不驗證嵌入的JSON)。

+0

謝謝:) 對於對象檢查,我做了this.proj!= null && typeof this.proj ==='object''但是'span'呢?在這種狀態下,它是一個對象,一個數組還是其他的東西? – DestyNova

+0

「跨度」將是您設置的任何JSON類型;最有可能是一個對象或數組。不幸的是,這些都是'typeof'「對象」,但是你可以使用'sails.util.isArray()'來測試數組('sails.util'包裝Lodash)。 – sgress454

+0

酷thx :)!我按照建議改變了我的模型,但在某些時候,深度關聯測試又如何? like(this.projCollab!= null && typeof this.projCollab ==='object')&&(this.projCollab.proj!= null && typeof this.projCollab.proj ==='object')){if (this.end DestyNova

相關問題