根据另一个集合中特定文档的存在,将集合中的文档发布到流星客户端(发布与关系)

Rog*_*rer 8 publish meteor

我有两个系列

  1. 优惠(相关领域:_ id)
  2. ShareRelations(相关领域:receiverIdofferId)

并且我只想向已登录用户发布已分享给他的优惠.

实际上,我是通过使用辅助数组(visibleOffers)来实现的,我通过循环为每个ShareRelations填充,然后在Offers.find上使用此数组作为$ in选择器.

我想知道这可能是这样做的流星方式,还是我可以用更少和/或更漂亮的代码?

我发布优惠的实际代码如下:

Meteor.publish('offersShared', function () {
  // check if the user is logged in
  if (this.userId) {
    // initialize helper array
    var visibleOffers = [];
    // initialize all shareRelations which the actual user is the receiver
    var shareRelations = ShareRelations.find({receiverId: this.userId});
    // check if such relations exist
    if (shareRelations.count()) {
      // loop trough all shareRelations and push the offerId to the array if the value isn't in the array actually
      shareRelations.forEach(function (shareRelation) {
        if (visibleOffers.indexOf(shareRelation.offerId) === -1) {
          visibleOffers.push(shareRelation.offerId);
        }
      });
    }
    // return offers which contain the _id in the array visibleOffers
    return Offers.find({_id:  { $in: visibleOffers } });
  } else {
    // return no offers if the user is not logged in
    return Offers.find(null);
  }
});
Run Code Online (Sandbox Code Playgroud)

此外,实际的解决方案的缺点是,如果正在创建新的共享关系,客户端上的商品集合不会立即更新新显示的商品(读取:需要页面重新加载.但我不确定这是否是因为这种发布方法或由于某些其他代码,这个问题不是主要的,因为这个问题).

Dav*_*don 9

您正在寻找的是反应性连接.您可以通过直接在发布功能中使用observe来完成此操作,或者使用库来为您完成此操作.预计Meteor核心在某些时候会有一个连接库,但在此之前我建议使用发布关系.看看文档,但我认为你想要的发布功能看起来像这样:

Meteor.publish('offersShared', function() {
  return Meteor.publishWithRelations({
    handle: this,
    collection: ShareRelations,
    filter: {receiverId: this.userId},
    mappings: [{collection: Offers, key: 'offerId'}]
  });
});
Run Code Online (Sandbox Code Playgroud)

这应该反应性地发布所有ShareRelations用户和所有相关的Offers.希望发布两者都不会成为问题.

PWR是一个非常合法的软件包 - 我们中的一些人在生产中使用它,Tom Coleman为此做出了贡献.我唯一要提醒你的是,在撰写本文时,大气中的当前版本(v0.1.5)有一个错误,会导致相当严重的内存泄漏.在它被撞之前,请参阅我的博客文章,了解如何运行更新的本地副本.

更新2/5/14:

发现流星博客有关于反应性连接的优秀帖子,我强烈推荐阅读.