How to update records of ongoing hierarchy in mongoose?

I have a record this way as below

1)

{ "name":"A", "parents":[ADMIN], "childrens":[B,C,D] } 

2)

  { "name":"B", "parents":[A], "childrens":[D,K,L] } 

3)

 { "name":"C", "parents":[B], "childrens":[K,L] } 

4)

 { "name":"D", "parents":[C], "childrens":[L] } 

Here, if you add a new entry "E" and make "C" as the parent, then the logic is the entry "E", which should be added as a child to the parent element "C'i.e for" B ", and at the same time, ā€œEā€ should also be added to the parent ā€œB.ā€ This logic is rather confusing when I start writing code and complicated, but I have achieved to some extent that I can make ā€œEā€ as a child of 'C', as well as the parent element 'C', but no further. My code:

 function (callback) { var item = {'employee' : employee.manager }; Employeehierarchy.find(item).exec(function (err, employeeparent) { if (employeeparent && employeeparent.length > 0) { Employeehierarchy.update( { _id: employeeparent[0]._id}, {"$push": { "childrens": employee._id } } ).exec(function (err, managerparent) { }); callback(err,employeeparent); } else{ callback(err,employeeparent); } } }); }, //Finding the parent record of the manager in hierarchy function (employeeparent, callback) { var item = {'employee' : employeeparent[0].parents }; Employeehierarchy.find(item).exec(function (err, managerparent) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { if (managerparent && managerparent.length > 0) {console.log(managerparent+'managerparent') Employeehierarchy.update( { _id: managerparent[0]._id}, {"$push": { "childrens": employee._id } } ).exec(function (err, managerparent) { }); callback(err,managerparent); } else{ callback(err,managerparent); } } }); }else { callback(); } 
+1
source share

Source: https://habr.com/ru/post/1262408/


All Articles