[英]MongoDB: How to get main document and all ancestors
我需要创建一个出版物,该出版物为我提供了集合中的一组文档。 在这里您可以看到文档之间的相互关系:
{
"_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
});
您需要先执行.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()
进行此操作$or
但这可能会更慢。
您可以使用此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
的值更改时,发送给客户端的数据将不会更新
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.