MongoDB:如何获取主文档和所有祖先

时间:2016-11-15 20:49:56

标签: javascript mongodb meteor meteor-publications

我需要创建一个发布,它从集合中提供了一组文档。在这里您可以看到文档如何相互关联:

{ 
    "_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
});

2 个答案:

答案 0 :(得分: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);
  }
});

您也可以使用.find()使用单个$or执行此操作,但这可能会更慢。

答案 1 :(得分:0)

您可以publish-composite在Meteor中发布加入关系:

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的值更改时,发送到客户端的数据将不会更新

相关问题