gpt4 book ai didi

meteor - 根据另一个集合中特定文档的存在,将集合中的文档发布到 meteor 客户端(publish-with-relations)

转载 作者:行者123 更新时间:2023-12-04 07:23:11 24 4
gpt4 key购买 nike

我有两个收藏

  • 优惠(相关字段:_id)
  • ShareRelations(相关字段:receiverId 和 offerId)

  • 我只想向已共享给他的登录用户发布优惠。

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

    我想知道这是否可能是做到这一点的 meteor 方式,或者我是否可以用更少和/或更漂亮的代码来做?

    我发布优惠的实际代码如下:
    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);
    }
    });

    此外,实际解决方案的缺点是,如果正在创建新的共享关系,则客户端上的 Offers 集合不会立即使用新可见的优惠进行更新(阅读:需要重新加载页面。但我不确定这是否是因为这个发布方法或因为其他一些代码,这个问题不是主要的,因为这个问题)。

    最佳答案

    您正在寻找的是响应式(Reactive)连接。您可以通过直接在发布函数中使用观察来完成此操作,或者使用库为您完成此操作。 meteor 核心预计会有join library在某些时候,但在那之前我建议使用 publish-with-relations .查看文档,但我认为您想要的发布功能如下所示:

    Meteor.publish('offersShared', function() {
    return Meteor.publishWithRelations({
    handle: this,
    collection: ShareRelations,
    filter: {receiverId: this.userId},
    mappings: [{collection: Offers, key: 'offerId'}]
    });
    });
    这应该被动地发布所有 ShareRelations对于用户,以及所有关联的 Offers .希望发布两者都不会成为问题。
    PWR 是一个非常合法的包 - 我们中的一些人在生产中使用它, Tom Coleman对此做出贡献。我唯一要提醒您的是,在撰写本文时,目前的大气版本 (v0.1.5) 存在一个错误,会导致相当严重的内存泄漏。直到它被撞到为止,请参阅我的 blog post关于如何运行更新的本地副本。
    2/5/14 更新:
    发现 meteor 博客在 reactive joins 上发表了一篇很棒的文章。我强烈推荐阅读。

    关于meteor - 根据另一个集合中特定文档的存在,将集合中的文档发布到 meteor 客户端(publish-with-relations),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20753279/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com