获取递归嵌套文档 - Mongoose / Mongodb

发布于 2024-12-02 15:56:27 字数 141 浏览 0 评论 0原文

我有一个递归嵌套模式,就像博客上的评论一样。将可能有几层深的单独嵌套文档拉出的最佳方法是什么?

据我所知,您可以获取根文档,然后深入到您想要的文档,但在递归情况下,所需文档的深度可能未知,我应该如何检索它。循环并执行 if 看看它是否正确......?

I have a recursively nested schema just like comments work on a blog. What is the best way to pull an individually nested document out which may be several layers deep.

I understand that you get the root document out, then drill down to the document you want, but in a recursive situation where the wanted document may be an unknown number of levels deep how should I retrive it. Loop through and do an if to see if its the correct one...?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤独难免 2024-12-09 15:56:27

看起来没有猫鼬方法可以做到这一点,所以我使用像这样的递归查找函数来查找嵌套的文件夹:

var findFolder = function(searchFolder ,folder_id, cb){
  var folder = searchFolder.folders.id(folder_id);
  if(folder == undefined){
    _.each(searchFolder.folders, function(subFolder){
      findFolder(subFolder, folder_id, cb);
    }.bind(this))
  }else{
    cb(folder);//when found callback passing the doc
  };
};

ps这使用下划线库

looks like there is no mongoose way to do it so im using a recursive find function like this for finding a folder which is nested:

var findFolder = function(searchFolder ,folder_id, cb){
  var folder = searchFolder.folders.id(folder_id);
  if(folder == undefined){
    _.each(searchFolder.folders, function(subFolder){
      findFolder(subFolder, folder_id, cb);
    }.bind(this))
  }else{
    cb(folder);//when found callback passing the doc
  };
};

p.s. this uses the underscore library

め可乐爱微笑 2024-12-09 15:56:27

快速回答是:您无法加载子文档,因为 mongodb 不支持它。在 mongodb 中,您可以仅加载根文档,然后在客户端(从任何深度级别)从中提取子文档。

Quick answer is: you can't load sub document, because mongodb does not support it. In mongodb you can load only root document and then extract from it sub document at client side (from any level of deep).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文