2017-03-03 141 views
0

我正在使用React和createContainer。我正在寻找一种可以将两个电话连接在一起的方式。“链接”流星订阅

举例来说,如果我有这样的数据:

// Category 
{ 
    _id: 'ABC', 
    name: 'Cat 1' 
} 

// Item 
{ 
    catId: 'ABC', 
    slug: 'slug' 
} 

在我createContainer,我想通过它的塞(Items.find({ slug }))来获得Item。然后我想转过头来,并通过item.catId获得类别。

我想这样的事情,但它没有工作:

createContainer(({ slug }) => { 
    const itemHandler = Meteor.subscribe('Item.bySlug', slug); 
    const item = Items.findOne(); 

    const categoryHandler = Meteor.subscribe('Category.byId', (item.id || {}).id); // also tried just item.id and got undefined for item 
    const category = Categories.findOne(); 

    return { item, category }; 
}, Component); 

我能得到item就好了,但category没有骰子,它仍然是不确定的。我确信我没有被动地引发任何事情,但我不确定在这种情况下正确的模式是什么,或者如果有更简化的方式。

+0

这个包不适合你吗? https://atmospherejs.com/reywood/publish-composite – ffxsam

回答

0

事实证明,我发布的代码确实有效,我只是有一个数据问题,其中Items.categoryId没有正确填充。

在这个特殊的例子中,我确实想做一个客户端连接,我做了什么工作。项目位反应,一旦它加载,它实际上会重新运行,然后正确填充该字段。

createContainer(({ slug }) => { 
    const itemHandler = Meteor.subscribe('Item.bySlug', slug); 
    const item = Items.findOne(); 

    const categoryHandler = Meteor.subscribe('Category.byId', (item.id || {}).id); // also tried just item.id and got undefined for item 
    const category = Categories.findOne(); 

    return { item, category }; 
}, Component); 

通过,item第一次运行将被定义和category将为空。接下来通过(item准备就绪)然后将填充category。采取两跳,但工作得很好。

0

你基本上正在做一个客户端连接。在这些情况下,我通常会进行服务器端连接。在这里,在Item.bySlug出版商,我会做这样的事情:

let itemCursor = Items.find({slug: slug}); 

let transformItem = (fields) => { 
    // making an assumption here that Item has a categoryId that indicates its category 
    let category = Categories.findOne(fields.categoryId); 

    // attach the category to the Item 
    fields.category = category; 

    return fields; 
}; 

let handle = itemCursor.observeChanges({ 
    added: (id, fields) => { 
     fields = transformItem(fields); 
     this.added('items', id, fields); 
    }, 
    changed: (id, fields) => { 
     fields = transformItem(fields); 
     this.changed('items', id, fields); 
    }, 
    removed: (id) => { 
     this.removed('items', id); 
    } 
}); 

this.ready(); 

this.onStop(() => { 
    handle.stop(); 
}); 

现在,在客户端上,您只需要订阅你想要的项目,其类别将被连接。

3

您的问题最简单的办法是从服务器端返回publicationcursorsarraysubscription后调用collection.findOne()在客户端。

公布代码将是这样的:

Meteor.publish("your.publication.name", function(slug, id){ 
    let itemCursor = Items.find(your_selector); 
    let categoryCursor = Categories.find(your_selector); 
    return [itemCursor, categoryCursor]; 
}); 

现在,您将得到项目和类别收集必要的文件在客户端。

+0

当您从集合中发布单个文档并从另一个文档发布相关文档时,这是解决此特定问题的最简单解决方案。 –