2017-05-29 54 views
0

我的應用程序需要獲取此查詢的結果(這已經給出正確的結果在MongoDB中):查詢使用的NodeJS變量不工作,表達,mongojs和MongoDB

var denominator = db.getCollection('Transactions').aggregate({ 
    $group: { 
     "_id": null, 
     "Alltotal": {$sum:"$transAmount"} 
    } 
    }; 
    db.getCollection('Transactions').aggregate([{ 
    $group: { 
    _id: '$merchantCode', 
    total: { 
     $sum: { $multiply: ['$transAmount', 100 ]} 

}}}, 
    { $project: { 

     percentage: { 
     $divide: [ 
      "$total", 
      denominator.toArray()[0].Alltotal 
      ] 
     } 
    } 
} 
]) 

現在這裏是我如何我試圖執行它:

var express = require('express'); 
    var app = express(); 
    var mongojs = require('mongojs'); 
    var dbTransaction = mongojs('dataAnalysisDb',['Transactions']); 

    app.get('/Transactions',function(req,res){ 

    var denominator = dbTransaction.Transactions.aggregate([{ 
        $group: { 
          _id: 'null', 
          total: { $sum: '$transAmount' } 
         } 
         }]); 
    dbTransaction.Transactions.aggregate([{ 
    $group: { 
     _id: '$mtype', 
     total: { 
      $sum: { $multiply: ['$transAmount', 100 ]} 

    }}}, 
     { $project: { 
      percentage: { 
      $divide: [ 
       "$total", 
       denominator.toArray()[0].total 
       ] 
      } 
     } 
    }, 
    { $sort : { _id : 1, posts: 1 } } 
    ], function(err,docs){ 
    console.log(docs); //this is for testing 
    res.json(docs); 
    }); 
}); 

,我認爲這是行不通的,因爲我沒有正確的方式發送變量到服務器,當我使用它的操作也沒有定義。我將不勝感激任何關於如何修復它的建議。 謝謝

回答

0

我發現了一個辦法來解決它,它可能不是最好的,但它的工作,我離開這裏的不管是誰需要它

var denominator = dbTransaction.Transactions.aggregate([{ 
    $group: { 
      "_id": null, 
      "Alltotal": {$sum:"$transAmount"} 
    }}]).toArray(function(err,items){ 
     console.log(items[0].Alltotal); //this is for testiong 
     dbTransaction.Transactions.aggregate([{ 
      $group: { 
       _id: '$mtype', 
       total: { 
        $sum: { $multiply: ['$transAmount', 100 ]} 

       }}}, 
       { $project: { 
        percentage: { 
         $divide: [ 
         "$total", 
         items[0].Alltotal 
         ] 
        } 
       } 
      }, 
       { $sort : { _id : 1, posts: 1 } } 
      ],function(err,docs){ 
     console.log(docs); //this is for testing 
     res.json(docs); 
     }); 
     });