[英]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. 因此,我所知道的是第一个文档的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
});
You'll need to do a .findOne()
first then return an array of cursors: 您需要先执行
.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);
}
});
You could also do this with a single .find()
using an $or
but that would likely be slower. 您也可以使用
$or
单个.find()
进行此操作$or
但这可能会更慢。
You could this publish-composite to publish a join relationship in Meteor: 您可以使用此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
}
});
},
}],
};
});
This package makes sure that your publish is reactive, eg if the value of ancestors
changes the data published to client should be updated to reflect that change. 此软件包可确保您的发布是被动的,例如,如果
ancestors
的值发生更改,则应更新发布给客户端的数据以反映该更改。 If you just use findOne
in publication to get the ancestors
list, then the data sent to client will not be updated when the value of ancestors
change 如果您仅使用发布中的
findOne
来获取ancestors
列表,那么当ancestors
的值更改时,发送给客户端的数据将不会更新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.