我需要创建一个出版物,它为我提供了集合中的一组文档。在这里您可以看到文档如何相互关联:
{
"_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()
来完成此操作,但这可能会更慢。
关于javascript - MongoDB:如何获取主文档和所有祖先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40619440/