您走在正确的轨道上,但是如果我正确理解了您,那么您的设计就很糟糕。您不希望每次添加/删除卡片时都必须更新卡片组文档中的数组。在卡片文档中省略该cards字段会更容易,而是在卡片文档中添加一个deckId字段。虽然 MongoDB 通常鼓励嵌套/嵌入字段,但 Meteor 集合通常在典型的关系数据库样式模式下工作得更好。看看这个解决你的问题的方法:
甲板.js
Template.deckList.deck = () ->
Decks.findOne( _id: Session.get "deck" )
Template.deckList.cards = () ->
Cards.find( deckId: Session.get "deck" )
甲板列表.html
<template name="deckList">
<section class="deck-list">
<h1>{{#with deck}} {{title}} {{/with}} Deck</h1>
<ul class="cards">
{{#each cards}}
{{> card }}
{{/each}}
</ul>
</section>
</template>
<template name="card">
<li>{{foobar}}</li>
</template>
使用这种方法,您可以简单地在您的套牌中添加/删除卡片,并且更改将自动实时反映,而无需更新另一个数据库集合中的其他文档。
编辑:如果您想要一个多对多集合而不是一对多,您可以修改服务器上的发布方法以返回特定卡组的卡片,并避免将该连接表发布到客户。它可能看起来像:
// Server publish method
// Return just cards that are in deck "deckId"
Meteor.publish('cards', function (deckId) {
var cardIds = CardsDecks.find({ deckId: deckId }).map(function (connector) {
return connector.cardId;
});
return Cards.find({ _id: {$in: cardIds } });
});
// Client subscribe method
Meteor.subscribe('cards', Session.get('currentDeckId')); // Get just the cards related to the current deck
干杯!
注意:这最初是在CodersClan上回答的