猫鼬递归填充 [英] mongoose recursive populate

查看:23
本文介绍了猫鼬递归填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了一段时间,但没有找到任何好的答案.我有 n-deep 树存储在数据库中,我想填充所有父级,所以最后我得到了完整的树

I have been searching for a while and I didn't find any good answer. I have n-deep tree that I am storing in DB and I would like to populate all parents so in the end I get the full tree

node
 -parent
  -parent
    .
    .
    -parent

到目前为止,我填充到第 2 级,正如我提到的,我需要达到 n 级.

So far I populate to level 2, and as I mentioned I need to get to level n.

Node.find().populate('parent').exec(function (err, items) {
   if (!err) {
     Node.populate(items, {path: 'parent.parent'}, function (err, data) {
       return res.send(data);
     });
   } else {
     res.statusCode = code;
     return res.send(err.message);
   }
 });

推荐答案

只是不要 :)

没有好的方法可以做到这一点.即使您进行了一些 map-reduce,如果您拥有或将需要它,它也会有糟糕的性能和分片问题.

There is no good way to do that. Even if you do some map-reduce, it will have terrible performance and problems with sharding if you have it or will ever need it.

Mongo 作为 NoSQL 数据库非常适合存储树文档.如果您没有很多查找特定叶子"查询,您可以存储整棵树,然后使用 map-reduce 从中获取一些特定叶子.如果这对您不起作用,请使用两个集合:

Mongo as NoSQL database is really great for storing tree documents. You can store whole tree and then use map-reduce to get some particular leafs from it if you don't have a lot of "find particular leaf" queries. If this doesn't work for you, go with two collections:

  1. 简化树结构:{_id: "tree1", tree: {1: [2, {3: [4, {5: 6}, 7]}]}}.数字只是节点的 ID.这样,您将在一次查询中获得整个文档.然后您只需提取所有 ID 并运行第二个查询.

  1. Simplified tree structure: {_id: "tree1", tree: {1: [2, {3: [4, {5: 6}, 7]}]}}. Numbers are just IDs of nodes. This way you'll get whole document in one query. Then you just extract all ids and run second query.

节点:{_id: 1, data: "something"}, {_id: 2, data: "something else"}.

然后您可以编写简单的循环函数,该函数将用第二个集合中的数据替换第一个集合中的节点 ID.2 个查询和简单的客户端处理.

Then you can write simple recurring function which will replace node ids from first collection with data from second. 2 queries and simple client-side processing.

小更新:

您可以扩展第二个集合,使其更加灵活:

You can extend second collection to be a little more flexible:

{_id: 2, data: "something", children:[3, 7], parents: [1, 12, 13]}

这样您就可以从任何叶子开始搜索.然后,使用 map-reduce 到达这部分树的顶部或底部.

This way you'll be able to start your search from any leaf. And then, use map-reduce to get to the top or to the bottom of this part of tree.

这篇关于猫鼬递归填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆