Organizing items within a group

As I embarked on my journey of creating my first Meteor app, I encountered a challenge that left me feeling a bit lost. I have a collection of Entries and I want to categorize them by date, not simply sort them. Each entry comes with a date and I envision building a timeline-like structure. Here's an example of what one of the entries looks like:

{
  "_id": "xHmfEc5gMmGzDZgD2",
  "title": "something",
  "labels": [
    "pv4LnWNheyYRJqG7D"
  ],
  "images": [
    "zitE3FwmesHsNCxGG",
    "kYQTJYApDxPr4sMdW",
    "4enopyawfqBXRDvuh"
  ],
  "author": "TMviRL8otm3ZsddSt",
  "createdAt": "2016-01-31T21:05:55.401Z",
  "date": "2016-01-31T21:05:55.401Z",
  "description": "description"
}

Ultimately, I aim to create a timeline where entries are grouped by days. Here's a glimpse of what the timeline could look like, with entries categorized by day:

Day - 11.02.2016

entry - xHmfEc5gMmGzDZgD2

entry - ZhmfEc5gMmGzDZg8z

entry - uafEc5gMmGzDZgD25

Day - 12.02.2016

entry - xHmfEc5gMmGzDZgD2

entry - ZhmfEc5gMmGzDZg8z

Day - 17.02.2016

entry - xHmfEc5gMmGzDZgD2

entry - ZhmfEc5gMmGzDZg8z

entry - xHmfEc5gMmGzDZgD2

entry - ZhmfEc5gMmGzDZg8z

Instead of creating a separate collection for a calendar, I would like to extract the days directly from the entries. Is there a way to accomplish this without making separate DB queries for each day?

I'm currently thinking of storing all the different dates from the entries in a separate collection and then having each day query the entries collection to fetch the relevant ones. However, I feel like this approach might not be efficient, as it would involve a DB query for each day...

Answer №1

For solving this issue, consider utilizing the aggregation framework. However, since aggregate is not yet supported in meteor, you will need to install the aggregation framework package - it simply wraps up some Mongo methods for you.

Simply add meteorhacks:aggregate to your Meteor project and you will have proper aggregation support.

To achieve the desired result, use the following pipeline in the mongo shell:

var pipeline = [
    {
        "$project": {
            "yearMonthDay": { "$dateToString": { "format": "%Y-%m-%d", "date": "$date" } },         
        }
    },
    {
        "$group": {
            "_id": "$yearMonthDay",
            "entries": { "$push": "$_id" }
        }
    }
];

db.entry.aggregate(pipeline);

In Meteor, you can publish these results to the Entries collection on the client side:

Meteor.publish('getDayCategorisedEntries', function (opts) {

    var initializing = 1;

    function run(action) {

        // Define the aggregation pipeline ( aggregate(pipeline) )
        var pipeline = [
            {
                "$project": {
                    "yearMonthDay": { "$dateToString": { "format": "%Y-%m-%d", "date": "$date" } },         
                }
            },
            {
                "$group": {
                    "_id": "$yearMonthDay",
                    "entries": { "$push": "$_id" }
                }
            }
        ];

        Entries.aggregate(pipeline).forEach(function(e){
            this[action]('day-entries', e._id, e)
            this.ready()
        });
    };

    // Run the aggregation initially to add some data to your aggregation collection
    run('added');

    // Track any changes on the collection we are going to use for aggregation
    var handle = Entries.find({}).observeChanges({
        added(id) {
            if (initializing && initializing--) run('changed');
        },
        removed(id) {
            run('changed');
        },
        changed(id) {
            run('changed');
        },
        error(err) {
            throw new Meteor.Error('Uh oh! something went wrong!', err.message)
        }
    });

    // Stop observing the cursor when client unsubscribe.
    this.onStop(function () {
        handle.stop();
    });
});

The code above will observe changes and rerun the aggregation as needed.

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 automatically change the display of an element once the user has closed the menu?

How can I ensure that the display of an element remains unchanged when a user opens and closes my website menu using JavaScript? ...

Stop the default drag behavior on an input range element in VueJS

Is there a way to disable the default drag functionality of an input range element without affecting the click feature? Users should be able to change values by clicking instead of dragging. <input type="range" min="0" max=& ...

Understanding the Typescript Type for a JSON Schema Object

When working with JSON-schema objects in typescript, is there a specific type that should be associated with them? I currently have a method within my class that validates whether its members adhere to the dynamic json schema schema. This is how I am doing ...

The Vue method is failing to properly send data to an array of objects

Trying to troubleshoot this issue is proving to be quite challenging for me. Despite following all the guidelines, I seem to be stuck at a roadblock and cannot figure out what is causing the problem. Let's take a look at my vue.js application: new Vu ...

It appears that the jQuery this() function is not functioning as expected

Despite all aspects of my simple form and validation working flawlessly, I am facing an issue where 'this' is referencing something unknown to me: $('#contact').validator().submit(function(e){ e.preventDefault(); $.ajax ...

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

Organizing various elements into separate divs with just one ajax request

I recently encountered an issue with my project involving an ajax call that was functioning correctly. $.get( 'accNoRealMovs1.jsp', {mode:"0"}, function(responseText){ $('#divAccMovementNR').html(responseTe ...

Ways to identify if the requested image is error-free (403 Forbidden)

One of my scripts loads an image from a specific source every 300 ms, but sometimes it receives a 403 Forbidden response. When this happens, the image element ends up blank. I want to find a way to verify if the image has received a valid 200 response befo ...

What is the best way to adjust the width of an image?

Can someone assist me with a script for implementing an auto read more feature on my blog? I have specified values for image thumbnail height and width in the script, but they are not being applied to my blog. Any help would be appreciated. To view my blo ...

Choose the initial unordered list within a specific division through Jquery

In a div, there is a ul. Inside a li, there is another ul. The task is to select only the first ul inside the div using jQuery. The HTML markup: <div class="parent"> <div class="clearfix"> <div class="another-div"> <ul cl ...

When you call setTimeout from a static function, it does not get executed

Having a problem with starting a timer in my utility typescript class. The static function initTimer() uses setTimeout but when called from a react component, the timer doesn't start. StyleWrapper.tsx const StyleWrapper: FC = (props) => { cons ...

Struggling to keep the page refreshed and stay on the same page in React, however, the state refuses to update as anticipated

My application is built using react, react-router-dom, and stitch for accessing MongoDB and handling authentication through Google. I am facing an issue where, after authenticating and accessing the ProtectedPage component, upon refreshing the page, the ...

Wait for response after clicking the button in Vue before proceeding

When the button is clicked for the first time and the data property is empty, I need to pause the button click code until an ajax response is received. Currently, when I press the button, both wait and scroll actions happen immediately without waiting for ...

An Unexpected Token Leads to a SyntaxError in Jest's CSS-Modules

I have successfully configured my jest to allow the usage of static files by following their detailed documentation. However, despite implementing the instructions correctly, I am still encountering an error: What steps can I take to resolve this issue an ...

Challenges faced with react-bootstrap-autosuggest

After spending the entire day attempting to integrate the package from here into my create-react-app project upon ejection, I encountered the following error: Failed to compile. Error in ./~/react-bootstrap-autosuggest/lib/Autosuggest.js Module not found ...

Utilizing AngularJS to invoke a particular function within a PHP script: A comprehensive guide

Utilizing AngularJS to interact with a PHP script, I am aiming to specifically call out individual functions. In the provided app.js script, the updatePost and deletePost functions are triggered by button clicks. While I've successfully separated the ...

Is there a way to execute a jar file using JavaScript?

Hello, I'm new to this and still learning. I have a jar file that takes one parameter and returns a JSON with the result. Could someone please advise me on how to run my jar using JavaScript? I've attempted the following code but it's not wo ...

Using MongoDB C# driver may result in enum serialization as an integer when applying LINQ filtering

I am currently working on querying a collection of GeoJSON data in a MongoDB database. The documents in this collection have a structure similar to the following: { "_id" : ObjectId("5db2d9d7a9912b215bb6bfc8"), "type" : "Feature", "properties" ...

Updating the value of the variable using ng-submit

My application displays Quantity: {{num}}. The default value is set to 3 in the scope. The objective is to click on: <form ng-submit="addContact()"> <input class="btn-primary" type="submit" value="Add Contact"> </form> and to up ...

Trouble installing NPM packages from Artifactory on Windows 10

Problem Description: I am utilizing Artifactory for my NPM packages. When attempting to install them on "Windows - 7", everything is functioning correctly. However, on "Windows - 10" an error is being displayed and the packages are not installing. Error M ...