【发布时间】:2023-03-15 04:35:01
【问题描述】:
我有两个收藏
- 优惠(相关字段:_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 集合不会立即更新为新可见的优惠(阅读:需要重新加载页面。但我不是确定是因为这个发布方法还是因为其他代码,这个问题不是主要的,因为这个问题)。
【问题讨论】:
-
虽然这是关系数据库中的常见模式,但要以 Meteor 方式实现这一点仍然有些棘手。你应该看看这个视频:eventedmind.com/posts/…
-
也许对数据进行非规范化并在 Offer 集合中添加
receiversId数组更简单?