Home > Software engineering >  Node Js how to fetch data from database in an hierarchical way
Node Js how to fetch data from database in an hierarchical way

Time:12-20

I'm writing a back code using NodeJs to fetch some data from backend, I want dataBase data to be like this like this:

data = [{
  name: "Admin",
  id: '1',
  children: [
    { name: "Admin", id: "1" },
    { name: "groupe1", id: "2" },
    {
      name: "groupe2", id: "1455", children: [
        { name: "groupe2", id: "1455" },
        { name: "gro", id: "5444" },
        { name: "hhrr", id: "45" }
      ]
    }
  ]
}]

the idea is simple we have a list of group each group has a parent I want to display all the groups list in an hierarchical way the top one of the tree is done Some groups are parents and groups in the same time and some others are only groups if the group is not parent we add an object with its name and ID in the array of children of his parent if this groups is a parent that's mean it has children we add an object with its ID and name in the array of children of his parents, and we add property children for the object which is array named children with for the first time an object with the name and the id of the group etc...

i tryed to do this but it did not work

const getParentsByType = async ({ name, _id }) => {

      let parentResult = [
        {
          id: _id,
          name: name,
          children: [
            {
              id: _id,
              name: name,
            },
          ],
        },
      ];
     parentResult= await findParent(_id, parentResult[0].children, 0);
     return parentResult;
    };

    const findParent = async (parentId, parentResult, itemPos) => {
      let children = await Models.GroupModel.find({ parent: parentId, status: true }).select('name  _id');
      for (let i = 0; i < children.length; i  ) {
        let childrenList = await Models.GroupModel.find({ parent: children[i]._id, status: true }).select('name  _id');
    
        if (childrenList.length != 0) {
          parentResult.push(buildParentWithChild(children[i]._id, children[i].name));
          findParent(children[i]._id,parentResult.children[i],itemPos  )
        } else {
          parentResult.push(buildParent(children[i]._id, children[i].name));
        }
      }
      return parentResult
    };

and this the model of the data base

const Group = mongoose.Schema({
  name: {
    type: String,
    required: true,
  },

  status: {
    type: Boolean,
    required: true,
  },
 
  
  parent: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Group',
  },
 
 

});

i had two days trying to resolve tis but with no result i need some helps and Thank you

CodePudding user response:

Try parsing your returned data. It validates your data as objects i dont see any problem with your function regardless i still have no idea what format your a trying to build.

let children = JSON.parse(JSON.stringify(await Models.GroupModel.find({ parent: parentId, status: true }).select('name  _id')));
let childrenList = JSON.parse(JSON.stringify(await Models.GroupModel.find({ parent: children[i]._id, status: true }).select('name  _id')));

CodePudding user response:

If I understand you right, you want to convert the array returned by Models.GroupModel.find, and which looks like

var dbresult = [
  {_id: "1", parent: null, name: "one"},
  {_id: "2", parent: "1", name: "two"}
];

into a hierarchical structure. This can be done with a function that adds all children of a given parent p, including, recursively, their children. Like the following:

function children(p) {
  var result = [];
  for (r of dbresult) if (r.parent === p) {
    var row = {_id: r._id, name: r.name};
    var chld = children(r._id);
    if (chld.length > 0) row.children = chld;
    result.push(row);
  }
  return result;
}
console.log(JSON.stringify(children(null)));

Note that this approach requires only one database access (to fill the dbresult) and is therefore probably faster than your findParent function.

  • Related