Getting TypeError: Cannot read property 'rating' of null. While trying to get average rating


#1

I have two collections recipes and reviews and users can review a recipe and can rate it from 1 to 5 and i am trying to get the average rating of recipe but getting error Exception in template helper: TypeError: Cannot read property ‘rating’ of null. Can you please guide me what mistake i am making and how to solve it.

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 get 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);
    }
})

#2

you can use findOne here

var reviews = Reviews.findOne({recipeId: Router.current().data()._id});

just using find() makes reviews a cursor, so you can’t use that in the _.pluck() method.

findOne will return an object that can pluck the rating key from.