Any thoughts on making this better?
Score.aggregate([
{ $match: {
user_id: req.user._id
}},
{ $group: {
_id: req.user._id,
total_games_played: { $sum: 1 },
total_mass_eaten: {$sum: '$mass_eaten'},
average_score: { $avg: '$highest_mass' },
highest_score: { $max: '$highest_mass' },
best_survival_time: { $max: '$survival_time' },
most_cells_eaten: { $max: '$cells_eaten' }
}}
], function(err, result) {
if (err) return res.status(400).send(err);
User.findById(req.user._id, function(err, user) {
if (err) {
return res.status(400).send(err);
} else {
user.total_games_played = result[0].total_games_played;
user.total_mass_eaten = result[0].total_mass_eaten;
user.average_score = result[0].average_score;
user.highest_score = result[0].highest_score;
user.best_survival_time = result[0].best_survival_time;
user.most_cells_eaten = result[0].most_cells_eaten;
user.updated = new Date();
user.save(function(err) {
if (err) { return res.status(400).send(err); }
res.json(user);
});
}
});
});