我在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);
});
答案 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);
});
});
})