我是MEANJS的新手,我遇到了一个问题,即有一个名为employee
的集合,有多个文档的boss
字段。现在我想得到所有员工的较低级别。
例如:
1){_id:ObjectId('587dcd3edca5f235f862fdfd'), name:'John'} //he doesn't have boss
2){_id:ObjectId('587dcd3edca5f235f86dddew'), name: 'Jimmy', 'boss': ObjectId('587dcd3edca5f235f862fdfd')} //john is boss
3){_id:ObjectId('587dcd3edca5f235f863ew'), name: 'David', 'boss': ObjectId('587dcd3edca5f235f86dddew')} //john,Jimmy are bosses
4){_id:ObjectId('587dcd3edca5f235f86qwa'), name: 'Dyan', 'boss': ObjectId('587dcd3edca5f235f86dddew')} //john,Jimmy,David are bosses
5){_id:ObjectId('587dcd3edca5f235f8ew32'), name:'Jack', 'boss': ObjectId('587dcd3edca5f235f862fdfd')} //john is boss
6){_id:ObjectId('587dcd3edca5f2wsw23rlot'), name: 'Loren', 'boss':ObjectId('587dcd3edca5f235f8ew32')} //john,Jack is boss
如果我们把
Jonh则输出将为['Jimmy','Jack','David','Dyan','Loren']
插孔则输出将为['Loren']
下面是我的尝试代码:-
getBosses(user._id)
function getBosses(id){
User.find({boss:id})
.exec(function(err,users){
if(err)
return console.log(err);
//How handle here 'users' array
//for something getBosses call recursively
})
}
1条答案
按热度按时间wz3gfoph1#
据我所知,你需要找到那个人的所有下属。我认为最好的方法是使用
$graphLookup
。第一个
最后一个的结果是:
最重要的是聚合管道的
$graphLookup
阶段。最后两个$project
阶段只是响应格式化-只返回name
和subordinates
作为字符串字段,名称以逗号分隔。要获取特定人员的数据,您可以在
$graphLookup
之前使用$match
stage,如下所示: