Im using Node.js with Mongoose to Store data in MongoDB.
I need to show a list of all the users with their current available balance. I tried using multiple for loops, but I kept getting errors somewhere or the other. I'm able to show the list of unique users, but summation of their balance is incorrect. I felt I was doing it the wrong way. Could someone suggest a good way to get my required output with lesser and pretty code?
Current Data in My 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 I 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);
});