When it comes to my collections of recipes and reviews, users are able to review a recipe and rate it from 1 to 5. I am currently encountering an error while attempting to calculate the average rating of a recipe: Exception in template helper: TypeError: Cannot read property 'rating' of null. Can anyone provide guidance on what mistake I may be making and how to resolve this issue?
collections.js
Recipes = new Mongo.Collection('recipes');
Reviews = new Mongo.Collection('reviews');
add_review.js
Template.add_review.events({
'submit .add-review':function(event){
var rating = event.target.rating.value;
var review = event.target.review.value;
Reviews.insert({
rating:rating,
review:review,
recipeId:Router.current().data()._id
});
return false;
})
helper to calculate average rating
Template.reviews.helpers({
averageRating: function() {
var reviews = Reviews.find({recipeId: Router.current().data()._id});
var ratings = _.pluck(reviews, 'rating');
var sum = ratings.reduce(function(pv, cv){return pv + cv;}, 0);
var avg = sum / ratings.length;
return Math.round(avg);
}
})