Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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);
            });
        }
    });
});
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.