Monday, 29 May 2017

Query with variables not working using nodejs ,express, mongojs and mongodb

My application needs to get the result of this query (this is already giving the correct result in 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
          ] 
      } 
   }
 }
])

Now here is how I am trying to execute it:

  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);
   });
 });

I think this is not working because I am not sending the variable in the correct way to the server and when I use it on the operation it is not defined. I will appreciate any suggestion on how to fix it. Thank you



via R.martin

No comments:

Post a Comment