2016-06-08 57 views
0

大家好,我用我的項目Collection2使用,我希望得到一個字段,類型爲長度:從另一場陣流星Aldeed - Collection2 - 獲取數組字段的長度在autoValue

這裏是我的代碼示例

 yes: { 
      type: Array, 
      optional: true 
     }, 
     "yes.$": { 
      type: Object 
     }, 
     yesLength: { 
      type: Number, 
      autoValue: function(){ 
       var lenYes = this.field("yes").length; 
       console.log(this.field("yes")); 
       console.log(lenYes) 
       return lenYes; 
      }, 
      optional: false 
     }, 

當我登錄this.field(「是」)到控制檯,看起來很好,但是當我登錄lenYes即this.field(「是」),長度,我得到未定義。我在這裏做錯了什麼?謝謝

回答

0

在Collection2中,如果它們是$set中的修飾符,您只能得到其他字段的值。這通常不是這種情況,在這種情況下,您需要實際上.findOne()來獲取文檔,然後從中獲取當前值。

你可以認爲Collection2作爲一個驗證器改變但它不是電流值一個驗證。

由於您的yesLength應該代表一個數組,數組的長度的長度可以在許多不可預知的方式被修改,可能更有意義,使用collection hook計算yesLength的更新而改變。

MyCollection.after.insert(function(userId,doc){ 
    if (doc.yes){ // the yes array exists 
    MyCollection.direct.update(doc._id,{ $set: { yesLength: doc.yes.length }}); 
    } 
}); 

MyCollection.after.update(function(userId,doc,fieldNames){ 
    if (fieldNames.indexOf('yes') > -1) { // yes array was modified 
    MyCollection.direct.update(doc._id,{ $set: { yesLength: doc.yes.length }}); 
    } 
}); 

您需要使用.direct,以避免重新進入你的鉤子,當你更新計數器。

+0

謝謝@michelFloyd。我有一個解決我想要實現的方法。我希望yesLength字段的值設置爲「是」字段的長度,該字段是數組 – Kenshinman

+0

,查看已更新的答案。 –

+0

嗨,謝謝,但我在調用方法'/ questions/update'時在控制檯_Exception中遇到了這個錯誤。錯誤:在篩選出不在模式中的密鑰後,當我嘗試更新或插入我的集合時,您的修改器現在是空的 – Kenshinman