What is the best way to calculate the total number of reviews?

I am looking to calculate the total number of reviews for a specific recipe and display those reviews on the recipes.html page, which showcases all available recipes. Although I have attempted to utilize the countReviews helper as a global helper, it does not seem to function properly on the recipes.html page. Can someone provide assistance in accurately counting the reviews for recipes and showcasing them on the recipes.html?

For the complete source code, please visit Github.

collections.js

Recipes = new Mongo.Collection('recipes');
Reviews = new Mongo.Collection('reviews');
RecipesImages = new FS.Collection("recipesImages", {
    stores: [new FS.Store.GridFS("recipesImages")]
});

reviews.js

 Template.reviews.helpers({
        'showReviews': function () {
            return Reviews.find({recipeId: Router.current().data()._id})
        },

        countReviews: function(){
            return Reviews.find({recipeId: Router.current().data()._id}).count();
        }});

add_reviews.js

Template.add_review.events({
    'submit .add-review':function(event){
        event.preventDefault();
        var rating = event.target.rating.value;
        var review = event.target.review.value;
        var recipeId = Router.current().data()._id;
        addReview(rating,review,recipeId);
    }
});

recipes.html

<template name="recipes">
    <div class="container">
        <div class="row">
            {{#each showRecipes}}
                {{#if showRecipes}}
                    <div class=" col-md-4">
                        <a class=".deco-none" href="{{pathFor 'show_recipe'}}">
                            <div class="panel panel-default mb " >
                                <div class="panel-image">
                                    <img src="{{images.url storage='recipesImages'}}" class="panel-image-preview" />
                                </div>
                                <div class="panel-body pb">
                                    <h4>{{name}}</h4>
                                    {{shortText description 100}}
                                </div>
                                <div class="  panel-footer text-center" >
                                    <a href="{{pathFor 'show_recipe'}}" data-toggle="tooltip" title="View Recipe"><span class="glyphicon glyphicon-open-file"></span></a>
                                    <a href="#" data-toggle="tooltip" title="Cooking Time"><span class="glyphicon glyphicon-time" style="vertical-align:middle"></span><small> {{time}} Minutes</small></a>
                                    <a href="#" data-toggle="tooltip" title="Like it" data-action="addLikes"><span class=" glyphicon glyphicon-heart" style="vertical-align:middle"></span>&nbsp; <small>{{likes}} Likes </small></a>
                                    <a href="{{pathFor 'reviews'}}" data-toggle="tooltip" title="Reviews"><span class="glyphicon glyphicon-comment"></span></a>
                                </div>
                            </div>
                        </a>

                    </div>
                    {{/if}}
            {{else}}
                <h3>There are no recipes to show.Be the first one to add a recipe.<span class="required">(Log in required)</span></h3>

            {{/each}}
        </div>


    </div>

    <script>
        $(document).ready(function(){
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>
</template>

methods.js

addReview = function(rating,review,recipeId){
    if(review!=""){
        Reviews.insert({
            rating:rating,
            review:review,
            recipeId:recipeId
        });
        Router.go('reviews',{_id:recipeId});

        FlashMessages.sendSuccess('Review Added',{ autoHide: true, hideDelay: 2000 });
    }
    else{
        FlashMessages.sendError('Review field is empty',{ autoHide: true, hideDelay: 3000 });
    }
    return false;
};

upvote = function(currentRecipe){

    var user = Meteor.user();
    if(!user){
        FlashMessages.sendError("You need to login to like this recipe", {hideDelay: 1000});
        return false;

    }
    if (currentRecipe) {
        if (_.contains(currentRecipe.voters, Meteor.userId())) {
            FlashMessages.sendError("You already liked this recipe", {hideDelay: 1000});
            return false;
        }
        Recipes.update(currentRecipe._id, {$addToSet: {voters: 
Meteor.userId()}, $inc: {likes: 1}});
    }
};

Answer №1

Give this a try and inform me of the results:

suggestion

Template.recipes.helpers({
  getNumberOfReviews: function() {
    return Reviews.find({recipeId:this._id}).count();
  }
});

html

<a href="{{pathFor 'reviews'}}" data-toggle="tooltip" title="Reviews">
  <span class="glyphicon glyphicon-comment"></span>
  <small>{{getNumberOfReviews}} reviews</small>
</a>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to find the minimum and maximum intervals based on a consecutive property in a JavaScript Object?

Seeking assistance in calculating the maximum and minimum date differences (in hours or float days) for each location. When there is only one date interval for a location, consider the difference from the date above it. The data is already sorted by date ( ...

I'm trying to figure out how to upload a 3D model using Aframejs. It's working perfectly in threejs right now

After successfully creating a 3D animated model and running it in Three.js, I am now looking to use it in A-Frame for an AR app. var loader = new THREE.FBXLoader(); loader.load( 'model.fbx', function ( object ) { object.mixer ...

Display the text when the button is clicked

This section is designed to present a riddle. When you click the button, it reveals the answer. <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Puzzles</title> <link href="/css/favicon.ico" rel= ...

Post-execution function of forEach

I've been attempting to log messages using console.log() after a forEach function with Async/Await or Callback(). Unfortunately, neither of them is yielding the desired results. Below are the functions I'm working with: addAirports = async(airpo ...

Can one utilize Javascript/Angular to listen for a 'request sent' event trigger?

Is there a method in a Javascript/Angular application to intercept a 'request-sent' event triggered by the browser right after the request is sent out? Our goal is to manage and prioritize the order of outgoing requests, potentially sending each ...

The TypeAhead feature fails to display any search results for the entered query

Feeling really desperate right now! I'm facing a frustrating issue with Bootstrap Typeahead. Here is the HTML Markup: <div class="form-group"> <label for="">Recipients</label> <input id="recipients" name="recipients" ...

"Identify and extract specific elements within a complex, multi-layer

I have the following collection: [ { "array1": [ { "array2": [ { "array3": [ 1, 2 ] }, { "array3": [ 2, 3 ] }, { ...

Adjusting the size of the Toggle Switch component in Material UI

As a beginner in both Material UI and React, I'm having trouble adjusting the size of the toggle switch I'm implementing. Here's a simplified version of my code: import React, { Component } from "react"; import Switch from "@material-ui/co ...

Comprehending the process of sending a variable to Routes within Node.js

Hey there! I have a MongoDB functions file where I need to pass a value generated by a function to the routes file, but I'm having trouble figuring out how to do that. The file is called labels.js const findLabels = function(db, callback) { // Acc ...

AngularJS: Understanding the 'controller as' syntax and the importance of $watch

Is it possible to subscribe to property changes when using the controller as syntax? controller('TestCtrl', function ($scope) { this.name = 'Max'; this.changeName = function () { this.name = new Date(); } // not working ...

What is the best way to convert mm:ss into seconds with the help of momentjs?

In my current project using reactjs, I am faced with a challenge regarding time format. The frontend displays the time in the format "mm:ss" as shown in this example data: const data = [{ duration: "00:10" //I want to retrieve 10 seconds }, { duration: ...

How can I efficiently choose specific documents or items from a MongoDB collection when working within a loop?

I'm struggling to find the right approach for my current project. Essentially, I have a MongoDB collection that I am iterating through using forEach, displaying the objects in a table with ejs. My goal is to allow users to click on specific objects an ...

What is the process of generating a popup panel without relying on libraries, using JavaScript and CSS?

I'm currently working on creating a popup panel that is centered on the screen with rounded corners (scrollbars are unnecessary) using jQuery min, similar to this example: https://i.stack.imgur.com/0kYO6.png My progress so far: function (package) ...

How to pass model from NodeJS and ExpressJS to Knockout using Jade?

Currently, I am facing a challenge in passing my expressJS Model to my .jade template while trying to access the Model using JavaScript on the client-side. The concept is straightforward: I am looking to utilize the Model with Knockout.js, therefore requi ...

Examples showcasing the design of JavaScript APIs

I'm currently on the hunt for some top-notch examples of JavaScript APIs to use as inspiration for my own project. Please share any libraries with APIs that you admire, one recommendation per library. If you could also provide a brief explanation of w ...

The component is unable to access VueJS references

Below is a simplified version of the code I am working with: <html> <head> <script src="file:///D:/OtherWork/javascript/vue/vue.js"></script> </head> <body> <div id="app"> & ...

Challenges with Loading JSON Dynamically in Next.js using an NPM Package

In my TypeScript project, I have implemented a functionality where a json configuration file is dynamically loaded based on an enum value passed as a parameter to the getInstance function in my PlatformConfigurationFactory file. public static async getIn ...

What is the procedure for updating a user's password using mongoose?

I have a new feature on my website that allows users to reset their password if they forget it. Here are the packages I am using: Express Js (framework) passport-local--mongoose, passport-local, passport, I'm implementing the passport method . ...

What is the reason that TypeScript does not automatically infer void & {} as the never type?

When TypeScript's void type is used in combination with other types through intersection, the outcomes vary. type A = void & {} // A becomes void & {} type B = void & '1' // B becomes never type C = void & 1 // C becomes never type D = void ...

What is the best way to verify an array of objects within an asynchronous function?

I am struggling with validating an array of objects being sent to the server. It seems that my current code is not working properly when the array is empty or if the objects within it are invalid. I'm confused about why it's not functioning as ex ...