javascriptmongodbmeteormeteor-publications

MongoDB: How to get main document and all ancestors


I need to create a publication, which gives me a set of documents from the collection. Here you can see, how the documents are related to each other:

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

So what I know is the ID of the first document and I need also all ancestors in the publication.

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
});

Solution

  • You'll need to do a .findOne() first then return an array of cursors:

    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);
      }
    });
    

    You could also do this with a single .find() using an $or but that would likely be slower.