Meteor: Calculate the total count of items within a related collection

I am currently working on a lists/tasks application and have encountered an issue with counting the items for each list. I am using a session to store which list I am clicking on, but the count system is only related to that specific list. I followed the Meteor task board tutorial to determine how many items I have, but now I need to display the counter in front of each item in every list.

My main challenge lies in understanding how to count the items for each list and display the counter accordingly. In the tutorial, the counter is stored in Session. Should I create a new "counter" in the collection or continue using the session?

Below is some code snippet:

if (Meteor.isServer) {
    Meteor.publish('lists', function listsPublication() {
        return Lists.find({
            $or: [
               {private: { $ne: true}},
                {owner: this.userId},
            ],
        });
    });
}

Meteor.methods({

Template.list.helpers({
    incompleteCount() {
        return Tasks.find({ listId: Session.get('listId'), checked: { $ne: true } }).count();
    },

Template.list.events({
    'click .list-selected' (event) {
        event.preventDefault();

        var list = $(event.currentTarget).attr('list-id');
        Session.set('listId', list);
    },

Body.js

Template.body.helpers({
    tasks() {
        const instance = Template.instance();

        if (instance.state.get('hideCompleted')) {
            return Tasks.find({
                listId: Session.get('listId'),
                checked: { $ne: true },
            }, { sort: Session.get("sort_order") });
        }
        return Tasks.find({listId: Session.get('listId')}, { sort:      Session.get("sort_order")});
     },

     lists() {
         return Lists.find({}, { sort: { createdAt: -1 } });
     },

});

Any help or guidance would be greatly appreciated.

Answer №1

Special thanks to @CodeChimp for guiding me in the right direction. I managed to figure out a solution by simply using a parameter in my helper function:

    countIncompleteTasks(listId) {
        return Tasks.find({ listId: listId, checked: { $ne: true } }).count();
    },

Here is how I implemented it in my template (using jade):

   .ui.teal.left.pointing.label
        span {{countIncompleteTasks this._id}}

Previously, I was only able to search within one specific list, but by passing the parameter instead of relying on session.get(), I was able to dynamically update based on the active list.

Many thanks!

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

Encountering a Javascript Error when trying to begin

As a beginner in Javascript, I am venturing into designing a simple website that incorporates Javascript. Currently, my focus is on building a calculator. However, upon loading my website, nothing seems to initiate and there are no error messages displayed ...

In jQuery selectors, providing two variables may not yield any results, yet inputting the same string manually produces the desired output

For instance: let a = "1234"; let b = "line1\\\\.5"; Now, this particular code line: "#" + a + b; Produces the following string "#1234line1\\.5" And when I use it in the select ...

Enhance your image viewing experience with a React component that smoothly zooms in on images without distorting their dimensions, all with

After searching extensively for a solution, I have been unable to find one that works. My current setup involves using React with Bootstrap. I am in need of a stateless functional component that can take an image path as input and return an img element. Th ...

Node.js cannot access the uploaded image data as it has been defined as undefined

I have encountered an issue while sending an image file through ajax to my Node.js server. Upon attempting to view the file data, it returns 'undefined'. Here is a snippet from my app.js file: var express = require("express"); var app ...

Setting the expiry time for vue-cookie in hours Would you like to learn

I'm currently using the following code to set a 3-hour expiry for my vue-cookie: VueCookie.set('S3ID', getS3ID, 3); However, it seems that this function is actually setting the cookie expiry time as 3 days instead of 3 hours. Can anyone ex ...

Challenges in using HAML5 Canvas for mathematical applications

Hey there! I'm currently working on utilizing the canvas element to form various shapes, but I've encountered a few challenges when it comes to the mathematical aspect. Issue 1: I need to calculate an angle that is relative to the preceding line ...

Swapping out the default JavaScript random number generator for my custom JSON-based solution

I've been working on creating a D3 graph to display my data. After following a tutorial, I arrived at this particular piece of code: // 8. An array of objects of length N. Each object has key -> value pair, the key being "y" and the value is a r ...

How to open a hyperlink in a separate background tab with JavaScript or jQuery

I am in need of a feature that automatically opens all links on a website in a new background tab when a user clicks on them. Despite searching extensively, I have not found a solution that works across all browsers. To implement this, I have referred to t ...

Vue component fails to render due to a simple issue

I've been diving into Vue.JS and I'm facing an issue where the component I created isn't showing up on the page. Here's a snippet of my component: import Vue from 'vue' const card = new Vue({ el: '#card', data: ...

What is the best way to leverage TypeScript for destructuring from a sophisticated type structure?

Let's consider a scenario where I have a React functional component that I want to implement using props that are destructured for consistency with other components. The component in question is a checkbox that serves two roles based on the amount of ...

Detecting collisions with other objects in HTML/CSS/JavaScript while animating objects

Does anyone know how to create a dynamic character using css, html, and javascript, and detect collisions with other elements? Any suggestions or guidance would be greatly appreciated. ...

Interacting with YouTube Data API without requiring user input

I'm currently developing a music website that enables users to create YouTube playlists. Initially, I experimented with JavaScript: https://developers.google.com/youtube/v3/code_samples/javascript The procedure involves an initial authorization ste ...

Warning: The current version of graceful-fs (3) is deprecated in npm

I encountered an issue while running npm install. I attempted to run the following command before updating: $npm install npm, and also updated graceful-fs. $ npm install -g graceful-fs <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Having trouble assigning the current page in NextJS navigation

I have a unique setup for my navigation system in my NextJS project: const menu = [ { name: 'Home', href: '/home', icon: HomeIcon, current: true }, { name: 'About', href: '/about', icon: InfoIcon, current: fa ...

Transitioning from Startup mode to Secondary mode in MongoDB is a simple process that can

Struggling to switch STARTUP nodes to SECONDARY in MongoDB. After adding 3 nodes, 2 should be SECONDARY but are showing as STARTUP instead. Below are the details. Can't find a solution that matches my specific issue. Hello all, seeking guidance on ho ...

Guide to sending JSON data to a server and retrieving it back using AJAX - a detailed breakdown of the

As I work on my project web page, I am exploring the use of JSON to facilitate the transfer of data between the user and the server. However, I find myself a bit puzzled about the sequence of steps involved in each JSON method. Here is my current understan ...

Ways to retrieve the child number using JavaScript or PHP

Is there a way to retrieve the child number upon clicking? View screenshot For example, when I click on the X button, I want to remove that specific element. However, this action should only apply to item n2. In order to achieve this, I need to determine ...

Leveraging document.getElementById alongside css modules

When trying to retrieve an element that is using a css module, I encountered a problem where the id of the element changes after rendering. As a result, document.getElementById("modal") returns null. import React from "react"; export const HandleClick = ...

What is the process for integrating GitHub repository code into my client-side JavaScript application?

I am attempting to incorporate the GitHub repository "zipcelx" into my client-side JavaScript, but all I see is an option to download it from npm, which I do not understand. It would be helpful if someone could explain how a module meant for client-side us ...

Jquery Issue: Safari Leaves Alert Messages Unclosed When Opening Next Alert

I am experiencing an issue in Safari Browser and need some help with the following scenarios (with Example). When I click a button to delete an account, an alert message pops up. This alert window has two actions - "OK" and "Cancel". If I click "OK", it r ...