Skip to content

Instantly share code, notes, and snippets.

@AllStackDev1
Created December 3, 2018 18:22
Show Gist options
  • Save AllStackDev1/2319a3ceca16e2deefe780e1a0cd62b1 to your computer and use it in GitHub Desktop.
Save AllStackDev1/2319a3ceca16e2deefe780e1a0cd62b1 to your computer and use it in GitHub Desktop.
Trying to get user history of my app
// I use passport as auth so req.user is set by it.
// Is this code feasible enough when the user has many farms with different crops, i.e when the user data grows
// As of now the code taken up to 1412 ms to complete
const { Farm } = require('../models/farm');
getHistory = function(req, res, next) {
Farm.find().distinct('cropId', { userId: req.user._id }, (err, cropIds) => {
if (err) return res.send({ success: false, err });
let i = 0;
let data = [];
cropIds.some((entry, index) => {
data.push(
new Promise(function(res, rej) {
Farm.aggregate(
[
{
$match: {
$and: [{ userId: req.user._id }, { cropId: entry }]
}
},
{
$lookup: {
from: 'crops',
localField: 'cropId',
foreignField: '_id',
as: 'cropData'
}
},
{ $unwind: '$cropData' },
{
$project: {
amountInvested: 1,
returns: 1,
amountInvested: 1,
cropId: '$cropData._id',
cropName: '$cropData.name'
}
}
],
(err, farms) => {
if (err) return rej({ success: false, err });
let v = 0;
let AmountInvestedInThisCrop = 0;
let ReturnsFromThisCrop = 0;
let NoOfFarmsWithThisCrop = farms.length;
let cropId = farms[0]['cropId'];
let cropName = farms[0]['cropName'];
farms.some((entry, index) => {
AmountInvestedInThisCrop += entry.amountInvested;
ReturnsFromThisCrop += entry.returns;
});
res({
cropId,
cropName,
AmountInvestedInThisCrop,
ReturnsFromThisCrop,
NoOfFarmsWithThisCrop
});
}
);
})
);
});
Promise.all(data)
.then(resolve => {
let totalAmountInvested = 0;
let totalReturns = 0;
let totalFarms = 0;
let farmNames = [];
resolve.some((entry, index) => {
totalFarms += entry.NoOfFarmsWithThisCrop;
totalAmountInvested += entry.AmountInvestedInThisCrop;
totalReturns += entry.ReturnsFromThisCrop;
farmNames.push(entry.cropName);
});
const historyData = {
totalFarms,
totalAmountInvested,
totalReturns,
farmNames
};
res.send({ success: true, data: resolve, historyData });
})
.catch(reject => {
console.log(reject);
// res.send({ success: false, err: resolve });
});
});
};
module.exports = getHistory;
@OliverMensahDev
Copy link

Not bad but creating promises for each entry? Is it possible to create a single promise that can be used for each data

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment