简体   繁体   中英

How to loop save array of objects to mongodb

I want to store this data to mongodb, But I don't know how to loop it, Tried for a long time and couldn't get the correct answer

There is tree data

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

There is my Schema

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

I hope to get this result

{ _id: 5dea0671855f5d4b44774afd, name: 'A', parent: null, },
{ _id: 5dea07383ef7973e80883efd, name: 'A1', parent: 5dea0671855f5d4b44774afd, },
{ _id: 5dea07461047036d7c958771, name: 'A11', parent: 5dea07383ef7973e80883efd, },
{ _id: 5def00c05de2b22f8e6b9bfe, name: 'A2', parent: 5dea0671855f5d4b44774afd, },
...

This problem has troubled me for a long time, hope to get everyone's help, thank you!

  1. Create ID and flat
  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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM