Calculating the average count in Meteor using Mongo database

Imagine having a document structured like this

{
    "_id" : "PQ8GUYYB7IERPNE9NX-CombQQD7F",
    "combId" : 5,
    "alignToOffer" : true,
    "product" : "TwBuYJZquKeKTmtwr",
    "price" : 85,
}

Now, the goal is to calculate the average price for each combination of the same product when aligned (if the align option is checked). This can be achieved by using Meteor observe handle. By aggregating the average price values for related documents, we are able to track changes effectively.

Offers.find({}).observe({
   changed: function(offer, fields) {

      var result = Offers.aggregate(
          [
             {
                $match:
                {
                   product: offer.product,
                   status: true,
                   combId: Number(offer.combId)
                }
             },
             {
                $group:
                {
                   _id: "$product",
                   priceAlign: { $avg: "$price" },
                   minPrice: { $min: "$price" }
                }
             }
          ]
      );

      if (result.length){
         var averageValue = parseFloat(Math.round(result[0].priceAlign * 100) / 100).toFixed(2),
         bestOffer = parseFloat(Math.round(result[0].minPrice * 100) / 100).toFixed(2);
         var updateValues = { $set: {
            avgOffer: averageValue,
            bestOffer: bestOffer
         }};

         var updatePrice = { $set: {
            price : averageValue
         }};

         Offers.update({
            product: offer.product,
            combId: offer.combId,
            status: true
         }, updateValues, {multi: true});

         Offers.update({
            product: offer.product,
            combId: offer.combId,
            alignToOffer: true,
            status: true
         }, updatePrice, {multi: true});
      }
   }
});

While the above approach works flawlessly, there is a significant issue when saving the average price. To elaborate, let's assume we have three documents with the same product, where two are aligned (align to offer key checked) and one isn't. When the fixed value document's price (which is not aligned) is updated, the other two will save with an increment or decrement of decimal places instead of the exact price. For instance, updating the fixed price to 96 may result in the other prices being saved as 95.99999999999996 or 96.00000000000001 rather than just 96. Achieving a whole number without any decimals seems challenging even with methods like toFixed() in vanilla JS. Any guidance on resolving this enigma would be highly appreciated.

The most recent change still yields 96.01 or 95.99

Answer №1

To calculate the average, you don't have to add extra logic. Just follow the steps below or utilize the $avg operator in mongoDB.

1) Start by retrieving all documents that have the field alignToOffer: false.

2) Once you have gathered these documents, you can find the average using aggregation methods or manually compute it as shown below.

3) Update those documents with alignToOffer: true to reflect the calculated average price.

1)

let result = Offers.find({
         product: offer.product,
         status: true,
         alignToOffer: false,
         combId: Number(offer.combId)
 }).fetch();  //use fetch for meteor framework.

2)

// If only one document is returned, set its price directly without averaging
let avg = result.length > 1 ?
result.map(obj => obj.price).reduce((o,n) => o + n) / result.length :
result[0].price;

3)

Offers.update({
         product: offer.product,
         alignToOffer: true,
         status: true,
         combId: Number(offer.combId)
}, {$set:{ price : Number(avg) }}, { multi: true });

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

Failing to catch the return value from a stored procedure in ASP Classic

Apologies for the lengthy post, but I wanted to provide all the necessary details. I am facing an issue with a JavaScript function that uses ajax to call some asp code, which then executes a stored procedure to check if a record already exists. Depending ...

When trying to use selenium.WebDriver, an error pops up: "missing ) after argument list."

Trying to extract content from the ::after element is proving to be a challenge. Despite my attempts, I keep encountering an exception: "OpenQA.Selenium.WebDriverException: "javascript error: missing ) after argument list My setup includes VSC, Selenium ...

navigation through sibling views using query-based route in ui-router

Imagine an app with two sides: "left" and "right", each with tabs. The application's URL structure is formatted like this: app/splitscreen/?leftTab=1&rightTab=1 Currently, the HTML template is set up as follows: <!-- splitscreen.tpl.html --& ...

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...

Does clip-path jump at the top because of JavaScript offset?

When hovering on the box, a circle appears and moves based on JavaScript offset values. However, when the circle reaches the second paragraph element, it jumps to the top. I am looking to understand why this is happening and how to ensure smooth movement o ...

Issue encountered while serializing data in next.js when utilizing getServerSideProps function

Encountering An Error Error: The error message "Error serializing .myBlogs returned from getServerSideProps in "/blog"" keeps popping up. I'm facing a problem while attempting to log the data! Initially, when I was fetching data using use ...

The code trigger is malfunctioning: Unhandled Jquery error detected

Currently, I am attempting to activate the first anchor element of the unordered list using jQuery. However, I keep encountering an error that says Uncaught TypeError: Cannot read property 'type' of undefined. I am unsure why this is happening an ...

Retrieving information from MongoDB and Electron JS through IPC renderer

programming file this.$electron.ipcRenderer.send('get-result') this.$electron.ipcRenderer.on('got-it', (event, data) => { if (data.status) { this.allResult = data.result } else{ thi ...

How can AngularJS utilize ng-repeat and ng-bind-html to display arrays of HTML strings?

I'm currently attempting to display HTML strings from an array of HTML strings in my AngularJS project. As a newcomer to AngularJS, I have been trying to follow the examples provided on the official AngularJS website, but I am struggling to find a sui ...

the mobile website is not properly aligned on a horizontal axis

As I work on creating a mobile version of my website, I've come across a challenge: The entire site fits perfectly on the computer at a browser width of 480px, but when viewed on my mobile phone (regardless of the browser used), it leaves space on the ...

Obtaining the variable name from JSON using Javascript's XMLHttpRequest

JSON: { dynamicname1: { 0: "x", 7: "y", .... }, dynamicname2: { 0: "xx", 7: "yy", 14: "zz", ... } } dynamicname1 and dynamicname2 are generated dynamically for each request m ...

Tips for changing images when hovering over them

Currently engaged in the development of an e-commerce application, where I am looking to accomplish a specific task... https://i.sstatic.net/sYoG8.png The objective is to display the corresponding large image on the big box when hovering over smaller ima ...

Incorporating an array of JSON into a Mongoose schema in JavaScript

I am currently developing an Android App focused on baseball, and I have decided to use MongoDB to store my data. The format in which I would like my JSON data stored in the database is as follows: {"<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

What steps do I need to take to generate a terrain similar to this using Three.js?

Trying to construct a terrain based on a heightmap with an enclosed bottom layer. Refer to this example for clarification: The current function for generating the terrain is as follows: var img = document.getElementById("landscape-image"); var numSegment ...

Tips for customizing font color, size, and button color in a React project

My attempts to customize the price color, button color, and title font style have been unsuccessful. Despite my efforts, nothing seems to change. Additionally, I am unsure how to create a shadow effect. index.js index.js panel.js I tried changing the pr ...

How to Convert Python Lists into JavaScript?

octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} squidList = ["first", "second", "third"] for i in range(1): squid = random.choice(squidList) octopus = random. ...

Your browser's popup blocker is preventing the file from being downloaded

I am encountering an issue with my PHP file download function where the browser's popup blocker is preventing the file from opening. My objective is to create an HTML form submit button that will send a form, modify an RTF file on the server based on ...

How do I utilize ng-if in Angular to apply to only the parent tag and not the following markup?

Suppose I have two HTML elements with the same tag but different properties. How can I conditionally select between them? Here are the two tags in question: <a ui-sref="root.one(::{param: value})"> <a target="_blank" href="{{::model}}"> I ne ...

`javascript pop up notification will only display one time`

I am currently developing a chrome extension with two different modes. When the user clicks on the icon, a pop-up message should appear to indicate which mode is active. However, I am facing an issue where the message does not always display when the pop- ...

Accessing Stencil through a corporate proxy network

As I embark on my inaugural Stencil project, I've encountered a puzzling error message: Cannot download "https://github.com/ionic-team/stencil- component-starter/archive/master .zip" Check your internet connection Error: connect ETIMEDOUT" De ...