【问题标题】:get all children recursively using a mongoose schema使用猫鼬模式递归获取所有孩子
【发布时间】:2017-04-09 09:41:28
【问题描述】:

我正在使用带有 mongoose 的 express 框架,并且我有以下 Schema:

var DocumentSchema = new Schema({
    name: String,
    description: String,
    parent: {
        type: Schema.Types.ObjectId,
        ref: "Document"
    },
    children: [{
        type: Schema.Types.ObjectId,
        ref: 'Document'
    }]
});

我正在尝试获取子级的动态层次结构树,但找不到任何合适的解决方案。

是否可以使用此架构来做到这一点?如果不是,我应该使用什么模式结构?

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-schema


    【解决方案1】:

    我不确定孩子的层次结构树是什么意思。所需数据输出的示例会有所帮助。

    如果您需要使用架构将特定节点的所有后代加载到平面结构中,您可以使用以下内容:

    getAllChildNodes(startNodeId, callback) {
      const tree = [];
      let idsToLoad = [];
    
      yourModel.findOne({_id: startNodeId }).exec((err, node) => {
        tree.push(node);
        idsToLoad = node.children;
        let count = 0;
    
        async.whilst(
          () => {
            return count < idsToLoad.length
          },
          (cb) => {
            yourModel.findOne({_id: idsToLoad[count] }).exec((err, doc) => {
              tree.push(doc);
              idsToLoad = idsToLoad.concat(doc.children);
              count++;
              cb();
            });
          },
          (err) => {
            if (err) {
              console.error(err);
              return callback(err);
            }
            return callback(null, tree);
          }
        );
    
      });
    }
    

    这可能是一个非常昂贵的查询,而且效率不高。如果这是您的主要用例,我不会推荐这种模式类型。如果您的数据是静态的,我会考虑使用Materialized PathsNested Sets

    【讨论】:

      猜你喜欢
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 2022-10-12
      • 1970-01-01
      • 2021-02-25
      相关资源
      最近更新 更多