2016-11-15 59 views
0

我需要创建一个出版物,该出版物为我提供了集合中的一组文档。在这里你可以看到,这些文件是如何相互关联的:MongoDB:如何获取主文档和所有祖先

{ 
    "_id" : "peRuJcPMDzZgTvWSX", 
    "author" : "author", 
    "type" : "article", 
    "parent" : "mnfTFfZ7Fqcu6ZJ7T", 
    "ancestors" : [ "hbSycmNNvmdqvpchX", "mnfTFfZ7Fqcu6ZJ7T" ] 
} 
{ 
    "_id" : "mnfTFfZ7Fqcu6ZJ7T", 
    "article" : "article", 
    "parent" : "hbSycmNNvmdqvpchX", 
    "ancestors" : [ "hbSycmNNvmdqvpchX" ] 
} 
{ 
    "_id" : "hbSycmNNvmdqvpchX", 
    "title" : "title", 
    "ancestors" : [ ] 
} 

所以我知道什么是头文件的ID,我还需要所有祖先的出版物。

Meteor.publish('list', function(id) { 
    check(id, String); 
    return Collection.find({}); // WRONG: gives me ALL documents 
    return Collection.find({ _id: id }) // WRONG: gives me only the first document (main) 
    // NEEDED: Main document and all ancestors 
}); 
+0

的价值听起来像是你将需要拉出主文档与'{更新_id:ID} '并且随后从该属性中拉出祖先 –

回答

1

你需要做的第一.findOne()然后返回游标的数组:

Meteor.publish('list', function(id) { 
    check(id, String); 
    const ancestors = Collection.findOne(id).ancestors; 
    if (ancestors){ 
    return [ Collection.find(id), Collection.find({_id: {$in: ancestors}})]; 
    } else { 
    return Collection.find(id); 
    } 
}); 

你也可以使用$or做到这一点有一个.find()但很可能会慢一些。

+0

'...祖先}}]中缺少')'。它不应该是数组中的逗号,而不是分号? – user3142695

+0

绝对正确!现在纠正了。 –

0

您可以将该publish-composite发布一个加入流星关系:

Meteor.publishComposite('list', function(id) { 
    // checking here ... 

    return { 
    find() { 
     return Collection.find(id); 
    }, 
    children: [{ 
     find(doc) { 
     return Collection.find({ 
      _id: { 
      $in: doc.ancestors 
      } 
     }); 
     }, 
    }], 
    }; 
}); 

这个包可以确保您的发布是被动的,例如如果ancestors的值更改,则发布到客户端的数据应更新以反映该更改。如果你只是使用findOne出版物获得ancestors列表,然后发送给客户端的数据不会被当ancestors变化