我有一个像下面这样的记录
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]
}
这里如果添加一个新记录'E'并将'C'作为父记录,则逻辑是记录'E'应作为子记录添加到'C'i.e的父亲为'B'同时'E'也应该添加到'B'的父级。当我开始编写代码和复杂时,这个逻辑非常令人困惑,但我在一定程度上实现了我可以让'E'成为一个孩子'C'和'C'的父母,但没有进一步。 我的代码:
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();
}