如何填充具有无限嵌套子级的文档?

问题描述

我有一个带有 childs 引用的树结构,我想通过 id 找到一个文档并用无限的嵌套子级填充它。

我想要这个结果:

[
      {
        _id: '60e884adb73aa620d0583e602',code: 'code1',value: 'value_1002',label: 'dechet_1002',childrens: [
          {
            _id: '60e88489b73aa620d0583e5f3',value: 'value_1001',label: 'dechet_1001',childrens: [
              {
                _id: '60e88444b73aa620d0583e5e5',value: 'value_1000',label: 'dechet_1000',childrens: []
              }
            ]
          }
        ]
      }
    ]

我尝试了 Pre hooks 或中间件函数,但它对我不起作用:

    // In the Model
    const mySchema = new mongoose.Schema(
      {
        label: {
          type: String,required: true
        },//...
        childrens: [
          {
            _id: {
              type: ObjectId,ref: 'patterns'
            },label: String,//...
          }
        ]
      },{ timestamps: true }
    );
   function autopopulateChildrens(next) {
     this.populate('childrens');
     next();
   }
            
     mySchema
       .pre('findOne',autopopulateChildrens)
       .pre('find',autopopulateChildrens)
       .pre('findById',autopopulateChildrens);
    const myModel = mongoose.model('patterns',mySchema);
    module.exports = myModel;
        
            // In the Controller
                await myModel
                          .findOne({_id: pId})
                          .select('_id label childrens')
                          .populate('childrens');

findById 和 findOne 对我不起作用。我还尝试将我的猫鼬更新到最新版本。我正在使用“猫鼬”:“^5.9.27”。

我尝试使用此功能手动执行此操作:

const getDescendants = async (pId) => {
  let descendants = [];
  let array = [];
  let item = await patternModel.findOne({ _id: pId });
  let { _id,code,value,label,childrens } = item;
  array.push({ _id,childrens });

  while (array.length > 0) {
    let currentnode = array.pop();
    let children = await patternModel.find({
      _id: { $in: currentnode.childrens }
    });

    children.forEach((child) => {
      let { _id,childrens } = child;
      descendants.push({ _id,childrens });
      if (child.childrens.length > 0) {
        array.push(child);
      }
    });
  }
  return descendants;
};

结果:

[
         {
            "_id":"60e884adb73aa620d0583e60","code":"code1","value":"value_1002","label":"dechet_1002","childrens":[
               {
                  "_id":"60e88489b73aa620d0583e5f","value":"value_1001","label":"dechet_1001"
               }
            ]
         },{
            "_id":"60e88489b73aa620d0583e5f","label":"dechet_1001","childrens":[
               {
                  "_id":"60e88444b73aa620d0583e5e","value":"value_1000","label":"dechet_1000"
               }
            ]
         },{
            "_id":"60e88444b73aa620d0583e5e","label":"dechet_1000","childrens":[]
         }
      ]

我想要的:

[
      {
        _id: '60e884adb73aa620d0583e602',childrens: []
              }
            ]
          }
        ]
      }
    ]

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)