如何将对象数组循环保存到mongodb

时间:2019-12-17 14:12:18

标签: javascript mongodb mongoose

我想将此数据存储到mongodb中,但我不知道如何循环它,尝试了很长时间并且无法获得正确的答案

有树数据

Started GET "/company/export_cs" for 127.0.0.1 at 2019-12-17 11:31:26 -0200
Processing by CompanyController#export_cs as HTML

有我的架构

[
  {
     name: 'A',
     children: [
       { 
         name: 'A1',
         children: [
           {
             name: 'A11',
             children: []
           }
         ]
       },
       {
         name: 'A2',
         children: []
       },
     ]
  },
  {
     name: 'B',
     children: [
       { 
          name: 'B1',
          children: []
       },
       { 
          name: 'B2',
          children: [
            {
              name: 'B21',
              children: []
            }
          ]
       },
     ]
  },
]

我希望得到这个结果

const TempSchema = new mongoose.Schema({
  name: String,
  parent: { type: ObjectId, ref: 'Temp' },
}

这个问题困扰了我很长时间,希望得到大家的帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

  1. 创建ID和单位
  const ObjectId = mongoose.Types.ObjectId;
  const flatten = (data, parent = null) =>
    data.flatMap(e => {
      e._id = ObjectId();
      return ([{
        _id: e._id,
        parent,
        name: e.name
      },
      ...flatten(e.children, e._id)])
    });
  const result = flatten(tree);

  await Model.insertMany(result)