NodeJS等待mongoDB查询的递归函数结果

时间:2018-10-20 17:01:25

标签: javascript node.js mongodb mongoose

  

solution:不将forEach与需要等待的功能一起使用。   使用一个简单的for函数并将await添加到该函数中。

我有一个猫鼬模式:

const TopicSchema = new mongoose.Schema({
    name: {type:String,unique:false},
    sub_topic:[{type:mongoose.Schema.Types.ObjectId, ref : 'Topic'}] 
});

每个主题可能都有子主题。 我想找到给定主题的所有子主题和子主题ID。 我编写了一个递归函数,以便每次都进行更深入的搜索并检索更多的子项。

Data now is : A-->
                  B-->no subs
                  C-->C1,C2
                  D-->D1,D2,D3

递归函数:

  async function getSubs(ID) {
    let subs = [];
    const topic = await Topic.findById(ID);
    console.log('-------in topic', topic.name)
    if (topic.sub_topic.length == 0) {
      //stop condition-no more subs just return array with id
      return [ID];
    }
    topic.sub_topic.forEach(function (sub) {
      subs.push(sub._id); //add current sub id to array
      var data = getSubs(sub._id)
        .then((data) => {
          subs = subs.concat(getSubs(data));
        });
    })
    return subs; //finally return all found subs
  }

这就是我调用它的方式:

app.get('/api/topic/subs/:id', (req, res, next) => {
let subs;
subs = getSubs(req.params.id)
  .then((subs) => {
    console.log('returned subs', subs)
  });

});

  

问题在于该函数返回子项,但不等待所有递归调用完成其添加更多子项的工作。   这是输出:

-------in topic A
returned subs [ 5bcb558ba68fb623e4d97ae1,
  5bcb558ba68fb623e4d97ae4,
  5bcb558ca68fb623e4d97ae5 ]
-------in topic C
-------in topic B
-------in topic D
-------in topic C1
-------in topic C2
-------in topic D2
-------in topic D1
...
...and so on

我如何让它等待其他通话结束?

-谢谢!

0 个答案:

没有答案