如何递归查找Mongoose数据?

up9lanfz  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(188)

我是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

    })
}
wz3gfoph

wz3gfoph1#

据我所知,你需要找到那个人的所有下属。我认为最好的方法是使用$graphLookup
第一个
最后一个的结果是:

[
  { name: 'John', subordinates: 'David, Dyan, Loren, Jack, Jimmy' },
  { name: 'Jimmy', subordinates: 'David, Dyan' },
  { name: 'David', subordinates: '' },
  { name: 'Dyan', subordinates: '' },
  { name: 'Jack', subordinates: 'Loren' },
  { name: 'Loren', subordinates: '' }
]

最重要的是聚合管道的$graphLookup阶段。最后两个$project阶段只是响应格式化-只返回namesubordinates作为字符串字段,名称以逗号分隔。
要获取特定人员的数据,您可以在$graphLookup之前使用$match stage,如下所示:

db.bosses.aggregate([
  { $match: { name: "John" } },
  {
    $graphLookup: ...

相关问题