node.js - How to get Current balance of each user from a bunch of transactions in MongoDB using NodeJS? -


im using node.js mongoose store data in mongodb.

i need show list of users current available balance. tried using multiple loops, kept getting errors somewhere or other. i'm able show list of unique users, summation of balance incorrect. felt doing wrong way. suggest way required output lesser , pretty code?

current data in database:

id    name    amount    credit      1     andy     500       true      2     andy    1000       false 3     tina     400       false 4     john     700       true 5     tina    2000       true  6     andy     100       true  7     tina     200       false  8     john     300       false  

required final output

 id    name   balance   1     andy    -400  2     tina    1400  3     john     400 

what have tried till now:

    accounts.find({}).exec(function (err, translist) {            var finalarr= [];            var currentamount = 0;           for(var i=0; i<translist.length; i++)           {                      if(translist[i].status===true) // credited                      {                            currentamount = currentamount + translist[i].amount;                      }                      else // debited                      {                            currentamount = currentamount - translist[i].amount;                      }                 if(i===0)                 {                  }                 else if (i===translist.length-1)                 {                         var obj  = {};                       obj._id  = translist[i]._id;                       obj.name  = translist[i].name;                       obj.amount = currentamount;                       finalarr.push(obj);                 }                 else                 {                    if(translist[i].student._id!=translist[i-1].student._id)                    {                        var obj  = {};                       obj._id  = translist[i-1]._id;                       obj.name  = translist[i-1].name;                       obj.amount = currentamount;                       finalarr.push(obj);                       currentamount = 0;                    }                                        }           }            data = json.stringify({list:finalarr});           res.end(data);          }); 


Comments

Popular posts from this blog

service - Android MediaPlayer calls onCompletion before it already finished -

javascript - Training Neural Network to play flappy bird with genetic algorithm - Why can't it learn? -

javascript - Create a stacked percentage column -