猫鼬递归人口 [英] mongoose recursive populate

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

问题描述

我已经搜索了一段时间,但找不到任何好的答案.我有 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天全站免登陆