How to update records on continues Hierarchy in mongoose?

回眸只為那壹抹淺笑 提交于 2019-12-11 04:46:09

问题


I have a record in such a way like 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 a add a new record 'E' and will make 'C' as parent ,then the logic is the record 'E' should be added as child to the parent of 'C'i.e for 'B' and at the same time 'E' should also be added to parent of 'B'.This logic is quite confusing when i start to write code and complex too but i achieved up to some extent that i can make 'E' as a child of 'C' and also the parent of 'C' but not 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();
}

来源:https://stackoverflow.com/questions/41506447/how-to-update-records-on-continues-hierarchy-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!