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

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

最佳答案

您需要先执行.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/

相关文章:

javascript - 是否需要在 iron-router@1.0.0-pre3 的服务器代码中定义 RouteControllers

node.js - Meteor.loginWithPassword 不适用于带有 @ 字符的用户名

javascript - 在 iframe 更改时滚动到父框架的顶部?

javascript - 使用 moment.js 验证 ISO 8601 日期

javascript - 允许输入自定义条目的 jQuery 组合框

javascript - 发送后无法设置 header

javascript - 在 iOS 中从网页执行 JS 函数

mongodb - 几个数组的交集

javascript - NodeJS 第一个 res.body 对象在引号中

meteor - 将 Paypal "Buy Now"按钮添加到 html 文件