concept average rating in category angular

appears as: average rating
Getting MEAN with Mongo, Express, Angular, and Node.js 2ED

This is an excerpt from Manning's book Getting MEAN with Mongo, Express, Angular, and Node.js 2ED.

When adding documents and subdocuments, you need to keep in mind any effect this action may have on other data. In Loc8r, for example, adding a review adds a new rating, and this new rating affects the overall rating for the document. On the successful save of a review, you’ll call another function to update the average rating.

Listing 6.8. Calculating and updating the average rating
const doSetAverageRating = (location) => {                        #1
  if (location.reviews && location.reviews.length > 0) {
    const count = location.reviews.length;
    const total = location.reviews.reduce((acc, {rating}) => {    #2
      return acc + rating;
    }, 0);
    location.rating = parseInt(total / count, 10);                #3
    location.save(err => {                                        #4
      if (err) {
        console.log(err);
      } else {
        console.log(`Average rating updated to ${location.rating}`);
       }
     });
  }
};
const updateAverageRating = (locationId) => {                     #5
  Loc.findById(locationId)
    .select('rating reviews')
    .exec((err, location) => {
      if (!err) {
        doSetAverageRating(location);
       }
     });
};