2015-05-21 42 views
0

我有一个Mongo集合的项目(项目)。我有另一个与项目相关的权限集合(item_ownership),其中一个权限存储拥有项目的用户的标识(owner_id)。我想获取用户拥有的所有项目并发布它们。 因此,理论上,我想先从'item_ownership'集合中选择item_id,然后将其插入'items'集合的查询中以对其进行过滤。这个过滤结果集将发布到浏览器:减少流星发送给浏览器的Mongo记录数量?

Items = new Mongo.Collection("items"); 
ItemOwnership = new Mongo.Collection("item_ownership"); 

Meteor.publish('items_pub', function() { 

     var itemOwnershipColl = ItemOwnership.find(
      { 
       owner_id: Meteor.userId() 
      }, 
      { 
       fields: { item_id: 1 } 
      } 
     ); 

     // Compile list of items to return. 
     var item_id_array = []; 
     itemOwnershipColl.forEach(function (record) { 
      item_id_array[item_id_array.length] = record.item_id; 
     }); 

     return Items.find(
      { 
       item_id: { $in: item_id_array } 
      }, 
      { 
       sort: { 
        item_order: 1 
       } 
      } 
     ); 
}); 

这是最好的方式去做这件事吗?

回答

1

如果我正确理解您的模式,看起来您的连接似乎是正确的。下面就来写一个方法:

Meteor.publish('items_pub', function() { 
    var selector = {owner_id: this.userId}; 
    var items = ItemOwnership.find(selector, {fields: {item_id: 1}}).fetch(); 
    var itemIds = _.pluck(items, '_id'); 
    return Items.find({_id: {$in: itemIds}}); 
}); 

它基本上是同样的事情,你的代码有一些快捷方式的更正:

  • 你失踪的初始查找之后fetch。没有它,你将无法访问文档。
  • _.pluck是一种将ID提取到数组中的更简单的方法。
  • 在发布中排序不是有用的,除非它与limitskip结合使用。见common mistakes
  • 我假设你的意思是在上次查找中搜索_id而不是item_id

同样值得注意的是,使用mongodb时,这种连接集合(ItemOwnership)通常是不必要的。一个更好的解决方案可能是在用户上存储一系列项目,或者在项目上存储用户数组。

+0

使用此方法(以及问题的原始方法)将导致非反应性连接。我通过使用Michael Floyd建议的软件包解决了我的问题。 – JoeTidee