从node.js中的嵌套回调中返回变量

时间:2017-04-29 16:20:22

标签: node.js callback

我在result中查询了我的查询结果,但我无法将其传递给浏览器,它显示为空。 如何将result返回res.send('result')

myApp.get('/agg',function(req,res){
MongoClient.connect(url, function(err, db) {
    // Execute aggregate, notice the pipeline is expressed as an Array
    db.collection('projects').aggregate([{$match:{school_state:"DC"}}, {$group:{_id: "$primary_focus_subject",total_amount:{$sum: "$total_donations"}}}],function(err,result){
    console.log(result);

    db.close();
    });
});

res.send(result);

});

1 个答案:

答案 0 :(得分:1)

你有2个解决方案:

  • res.send(result);放在console.log(result)

  • 的位置
  • 承诺包装您的MongoClient.connect,如下所示:

    let promise = new Promise((resolve,reject)=>{
      MongoClient.connect(url,function(err,db){
        db.collection('projects').aggregate([{$match:{school_state:"DC"}}, {$group:{_id: "$primary_focus_subject",total_amount:{$sum: "$total_donations"}}}],function(err,result){
          if(err) reject(err)
          resolve(result);
        });
      });    
    })