2016-03-07 27 views
2

我有SimpleSchema/Collection2這樣定義的集合:流星:如何自動填充存儲在集合中其他字段中的數組長度的字段?

Schema.Stuff = new SimpleSchema({ 
    pieces: { 
     type: [Boolean], 
    }, 
    num_pieces: { 
     type: Number, 
    }, 

我怎樣才能得到num_pieces到自動與pieces陣列每當有變化的長度填充?

我願意使用SimpleSchema的autoValuematb33:collection-hookspieces可能會與很多運營商進行更改,例如$push,$pull,$set,可能更多的是Mongo必須提供的,我不知道如何應對這些可能性。理想情況下,更新後只需查看pieces的值,但如何在不進入collection-hook的無限循環的情況下做出更改並進行更改?

回答

1

下面是你會怎麼做,防止無限循環「更新後」的集合掛鉤的例子:

Stuff.after.update(function (userId, doc, fieldNames, modifier, options) { 
    if((!this.previous.pieces && doc.pieces) || (this.previous.pieces.length !== doc.pieces.length) { 
    // Two cases to be in here: 
    // 1. We didn't have pieces before, but we do now. 
    // 2. We had pieces previous and now, but the values are different. 
    Stuff.update({ _id: doc._id }, { $set: { num_pieces: doc.pieces.length } }); 
    } 
}); 

注意this.previous,您可以訪問以前的文檔,doc是當前文檔。這應該足以完成其餘的案例。

+0

只是一個失蹤的,如果關閉托架,否則工作的魅力 - 謝謝! – Alveoli

0

你也可以這樣做是正確的架構

Schema.Stuff = new SimpleSchema({ 
    pieces: { 
    type: [Boolean], 
    }, 
    num_pieces: { 
    type: Number, 
    autoValue() { 
     const pieces = this.field('pieces'); 
     if (pieces.isSet) { 
     return pieces.value.length 
     } else { 
     this.unset(); 
     } 
    }  
    }, 
}); 
+0

有人早些時候發佈了相同的答案,現在已經刪除了它。我試過這個,並且它不起作用,因爲'pieces.value'引用了輸入修飾符,例如「真」,而不是結果字段值,例如'[假,真,真]' – Alveoli

相關問題