Reimagining data structures with Meteor and MongoDB for more streamlined and sophisticated code

Here is a link to a bin with all the required details: http://jsbin.com/ribor/1/edit?js,output

To make answering on SO easier, I will provide the model examples here:

Orders = {
  _id: "T487wBz7Pvzjo2QHh",
  beverages: [
    { 
      _id: "8ea26bb103efae385f80f881",
      delivered: false,
      name: "Wine",
      units: "55"
    }
  ],
  location: "yTKWLFwSDvp3DyCkx",
  locationName: "Ladies Garden",
  locationNumber: "101",
  timestamp: 1398393004864,
  user_id: "W3Fdq36Ts2TdWxCRP",
  username: "jgeezy"
};

Locations = {
  _id: "yTKWLFwSDvp3DyCkx",
  beverages: [
    {
      _id: "e5552a68266ed76895b8228a",
      fillTo: "10",
      name: "Wine Coolers",
      orderWhen: "10",
      startUnits: "10"
    }
  ],
  name: "Teen Cabana",
  number: "103",
  organization: "Super Happy Teens!",
  vendor: false
};

I am trying to create rows in a table for each location displaying the total number of undelivered beverage orders per location. Though I have a function written for this purpose:

Template.dashboardOrders.undeliveredOrders = ->
  undeliveredOrders = Orders.find({'beverages.delivered': false}, {
    transform: (order) ->
      order.unfilledOrders = 0
      _.each order.beverages, (bev) ->
        if not bev.delivered
          order.unfilledOrders += 1
      order
  })

The current output is an array sorted by Order and timestamp, whereas I need it sorted by unique location and timestamp. I've tried different map and reduce methods but haven't been successful. Any guidance on how to achieve this would be greatly appreciated!

BONUS Additionally, I feel my approach could be more elegant without having to return the order object and use += to increment. Perhaps there is a better way to handle this.

Answer №1

To address @jasongonzales' second question, I will now provide a second answer. The initial query returned all undelivered orders sorted by location and timestamp. In addition to this requirement, the following is also needed:

The goal is to include undelivered orders per location along with a count of these orders.

There are multiple approaches to achieve this objective. One effective method involves processing the data retrieved by the query rather than attempting to fit everything into the query itself:

Template.dashboardOrders.undeliveredOrdersByLocation = ->
  orders = Orders.find
      beverages.delivered: no
    ,
      sort:
        location: 1
        timestamp: 1

  # Utilize an object named locations to store undelivered orders organized by location;
  # Keys within the object represent location _id's while values consist of relevant mongo docs:
  locations = {}

  # Iterate through each undelivered order and add it to the respective entry in the locations object:
  orders.forEach (doc) ->
    unless locations[doc.location]?
      locations[doc.location] =
        undeliveredOrders: []
        undeliveredOrdersCount: 0
        location: doc.location
        locationName: doc.locationName
        locationNumber: doc.locationNumber
        # Additional fields based on template requirements 

    locations[doc.location].undeliveredOrders.push doc
    locations[doc.location].undeliveredOrdersCount++

  # Convert the locations object into an array for template usage:
  return _.values(locations) # Discarding keys as they are not needed

A sample template example was not provided, but you can incorporate the locations array in the following manner:

{{#each undeliveredOrdersByLocation}}
  Number of undelivered orders at {{locationName}}: {{undeliveredOrdersCount}}
    {{#each undeliveredOrders}}
      Order placed by {{username}} on {{timestamp}}, comprising:
        <ul>
          {{#each beverages}}
            <li>{{units}} units of {{name}} awaiting delivery.</li>
          {{/each}}
        </ul>
    {{/each}}
{{/each}}

Answer №2

Have you considered this approach instead?

Template.dashboardOrders.pendingOrders = ->
  Orders.find
      status: pending
    ,
      sort:
        dateCreated: 1
        timestamp: 1

What do you think of this solution?

If you prefer an array over a cursor, simply include .fetch() at the end.

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

Get rid of the .php extension in the URL completely

Lately, I've been experimenting a lot with the .php extension. I successfully used mod_rewrite (via .htaccess) to redirect from www.example.com/example.php to www.exmaple.com/example. Everything is running smoothly. However, I noticed that even though ...

Having difficulty accessing a JSON imported object beyond the FOR loop

I am facing an issue when trying to reference my imported JSON data. The problem arises when I attempt to access the data outside of a FOR loop, resulting in the error message "Uncaught TypeError: Cannot read property 'Tname' of undefined" The f ...

Running a Python Selenium script

I need some help executing this script using selenium. <div class="vbseo_liked"> <a href="http://www.jamiiforums.com/member.php?u=8355" rel="nofollow">Nyaralego</a> , <a href="http://www.jamiiforums.com/member.php?u=8870" rel="nofollo ...

I'm having trouble getting my JavaScript function to run all of the code

Can you please assist me in solving this problem by following this code snippet: function openNav() { document.getElementById("mySidenav").style.width = "250px"; document.getElementById("main").style.marginLeft = "250px"; document.getElementBy ...

Issue with MongoDB's addToSet function failing to add an element to an array

"mongoose": "^5.12.2" In my User schema, there is a field called "rol" which is of type string[] and is used for multiple roles in the application such as User, Admin, Freetour, BarOwner, etc. The function to add a new role to a user ...

in AngularJS, check for object attributes existence before proceeding to use them

Currently, I have a filter function that is designed to check the latitude and longitude distance of objects within an array against the range selected by the user. However, there is a problem in which some objects within the array do not possess latitude ...

Guide to delivering a PDF document from a controller

In my pursuit to send a PDF file from a Controller Endpoint using NestJs, I encountered an interesting issue. Without setting the Content-type header, the data returned by getDocumentFile function is successfully delivered to the user. However, when I do ...

When troubleshooting a basic Node.js CRUD API with Postman, an error stating "Cannot Post" is encountered. What steps can be taken to address this issue and resolve it?

I recently developed a Nodejs CRUD and authentication API. When testing the create operation for a new order in Postman, I encountered a status code of 404 with the response body 'Cannot Post'. Error: <html lang="en" ...

A guide on switching the status of various inputs in a table based on the selection of a radio button

In the scenario below, let's consider the following HTML structure: <tr> <td> <label for="c1_testRdio">Have you taken any tests in this class?:</label> <br> <label>Yes<input type="rad ...

How can you simultaneously start multiple tweens in Three.js using Tween chain?

Here's the current code snippet : function move(){ var A = new TWEEN.Tween(meshA.position).to({ z: -10 }, 2000).start(); var B = new TWEEN.Tween(meshB.rotation).to({ z: Math.PI }, 2000); var C = new TWEEN.Tween(meshC.position).to({ x: ...

Monitoring Local Host with MongoDB Service

Are there any MongoDB server performance monitoring tools available for running on a local host or machine? My main concern is privacy, as I am hesitant to use third-party hosting tools such as the MongoDB Monitoring Service. ...

Using JavaScript to implement word filtering in MongoDB

I'm currently in the process of creating a chatbot designed to filter questions, and I'm seeking guidance on how to refine the search in my MongoDb based on user input. At the moment, I have the following code: I aim to retrieve all the results ...

Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...

Extracting a precise data point stored in Mongo database

I have been struggling to extract a specific value from my MongoDB database in node.js. I have tried using both find() and findOne(), but I keep receiving an object-like output in the console. Here is the code snippet: const mongoose = require('mongoo ...

Struggling to store pushed data accurately into an array using node.js

) Currently, I am tackling a challenging node.js express custom API project. The issue arises when attempting to push data... This is the snippet of my code: module.exports = function(config, steamClient, csgo, database, teamspeakClient, router) { var a ...

Guide on synchronizing information from mongodb to elasticsearch through Logstash

I have a MongoDB database with data that I would like to visualize in real-time using Kibana. How can I set it up so that any changes made to the MongoDB data are reflected immediately in Kibana? I would appreciate any guidance on how to implement this s ...

Inserting a large array using Mongoose's insertMany method may not be as effective

Struggling to insert a large amount of data (400-1000 json object array) into mongodb using mongoose + expressjs. It works fine when inserting around 50 items with no issues, but once the data exceeds 100 items, it throws an error. Departed.insertMany(res ...

The heroku server in rails4 is experiencing issues with loading stylesheets, images, and javascript

Hey there! I'm currently facing a problem with my application. In my Gemfile, I've added the following code: group :production, :staging do gem 'rails_12factor' end Additionally, in my stylesheet named mytest.css.scss, I've inc ...

Aggregating nested documents in MongoDB

I am in possession of a document that is structured in the following manner: "summary":{ "HUL":{ "hr_0":{ "ts":None, "Insights":{ "sentiments":{ "pos":37, "neg":3 ...

When the tab on my website is clicked, the fontawesome icons elegantly transition into their designated positions

When my website loads, some of the fontawesome icons pop in after the animations finish. Specifically, two out of four icons used for visual representation of my skills (such as 'Sound Design' with a headphones picture) pop in when it gets to the ...