查询变量不能使用nodejs,express,mongojs和mongodb

时间:2017-05-29 17:13:05

标签: node.js express 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);
   });
 });

我认为这不起作用,因为我没有以正确的方式将变量发送到服务器,当我在操作中使用它时,它没有被定义。我将不胜感激任何关于如何解决它的建议。 谢谢

1 个答案:

答案 0 :(得分: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);
       });
       });