Tips for organizing a set by the contrast between two variables?

Each document in my collection contains two values that are structured as follows:

{
  originalPrice: 500,
  ourPrice: 420
}

I would like users to be able to sort by the savings they can make when shopping from us instead of a competitor, which in this case is 80.

However, since the saveAmount value is not stored in the database directly, I cannot simply perform a sort operation like this:

Goods.find({}, {sort: saveAmount: 1})

Inserting this number into the database could be a simple solution, but I am looking for an alternative approach unless it is too complex.

Therefore, I need a function like this:

var saveAmount = function(originalPrice, ourPrice) {
  return originalPrice - ourPrice
}

I want to utilize this function to sort the data. How can I achieve this?

Answer №1

In a MongoDB query, it is possible to achieve this task, although not with meteor. As such, a separate field must be used as suggested. The following approach can be taken:

function calculateDifference (doc) {
  var difference = doc.originalPrice - doc.ourPrice
  Goods.update(doc._id, { $set: { difference: difference } })
}

Goods.find().observe({
  added: calculateDifference,
  updated: calculateDifference
})

If simple-schema is in use, the autoValue method can be utilized.

...
difference: {
  type: Number,
  autoValue: function () {
    return this.field('originalPrice').value - this.field('ourPrice').value
  }
}
...

At this point, sorting by difference is made possible:

Goods.find({}, {sort: {difference: -1}})

Answer №2

Here is an illustration of how you can present the items in a sorted manner on the user's end:

Javascript

Template.myTemplate.helpers({
  displaySortedItems: function() {
    return _.sortBy(Items.find().fetch(), function(item) {
      return item.price - item.discount;
    });
  }
});

HTML

<template name="myTemplate">
  {{#each displaySortedItems}}
    <div class="item">{{name}}: ${{discountedPrice}}</div>
  {{/each}}
</template>

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

JavaScript keeps repeating as you perform basic addition operations

Dealing with a similar issue where things are not adding up correctly, I encountered a problem in a previous question about JavaScript variables only concatenating as strings. The pure JavaScript solution worked fine, so I have now consolidated all the cod ...

Is it possible for third parties to access the data transmitted via HTTPS POST requests?

When a user is logged in through a secure HTTPS AJAX POST request, does this ensure that the body of the HTTP POST is encrypted and hence protected? ...

What are Fabric.js tools for "Drop Zones"?

Has anyone successfully created a "drop zone" similar to interact.js using fabric.js? I haven't had the chance to experiment with it myself. I have some ideas on how I could potentially implement it, but before diving in, I wanted to see if anyone el ...

Error in AJAX transmission

I am encountering an unusual issue with the jQuery ajax function in my script. The problem is specific to my friend's computer, as I am not experiencing any difficulties on my own computer. While attempting to utilize the error function property to ...

Having trouble sending data from a page to a child component using getStaticProps

I'm currently working on a project using next.js and I'm facing an issue with passing data from the "gymlist" page to the "table" component. Here is the code snippet from the "gymlist" page where I have defined the getStaticProps function: expor ...

Issue with MongoDB and Node: Authorization error when attempting to run command (intermittent success)

I have encountered an issue with my MongoDB setup. Here is how it is configured: My node application offers a restify API that manages user registration by checking if a user exists in a collection based on their email, and inserting them if they do not e ...

Why is my return statement in JavaScript Nextjs mapping values twice?

I am running into an issue where my code is displaying the output twice, and I can't seem to figure out why. Any assistance would be greatly appreciated. Here is a link to the current output that I am receiving. I suspect that the problem lies in sett ...

Cause the browser icon to flash in the taskbar when a notification is received

After creating a monitor page for our product services, I wanted users to easily check the status of different services on that page. Now I am looking for a way to make the browser icon on the taskbar blink whenever there is an alert and the browser is mi ...

Parent scope receives directive updates with a slight delay

I recently made a transition of my simple paging feature from the controller to a directive, but encountered a peculiar issue. Whenever I update the parent scope from within the directive, the changes only reflect on the next alteration. For instance, if t ...

The ng-controller directive is not functioning accurately

I attempted to execute the following basic HTML: <!DOCTYPE html> <html ng-app="tempApp"> <head> <script src="js_libs/angular/angular.min.js"></script> <script src="js_libs/angular/bootstrap.js"></script&g ...

Injecting sinon js into an application within an iFrame: a step-by-step guide

I am looking to implement ajax requests testing in my application. The application is running within an iframe, and my goal is to have the iframe's wrapper page test the application using sinon (which will send the response). I attempted to include ...

Error while animating with jQuery

It's the wee hours of the morning and my jQuery skills are not the greatest. Can anyone point out the silly mistake I'm making? I've created a JSFiddle for easy access: http://jsfiddle.net/JamesKyle/7GWRp/ Due to an issue with CSS transiti ...

Transferring blank documents to a React-Native server

When attempting to send JSON files to the server using NodeJS with multer, I am running into an issue where the files are being sent empty. Currently, I am utilizing React-native-File-System to iterate through all the files located in the specified folder ...

Can you please enlighten me on how to obtain the HTML for the selected area of the cursor in Tiptap?

I've successfully created a customized text editing tool using tiptap/react. My question is, how can I retrieve the html or json of a selected area when I highlight text with the cursor? For instance, if I have a custom tag 'say-as' within ...

Dealing with net::ERR_CONNECTION_REFUSED in Axios on a Vue.js platform

Here's the code I'm using for my connection request: doLogin(this.login).then(response => { var token = response.data.token; localStorage.setItem('AUTH_TOKEN', JSON.stringify(token)); this.$router.push({name: ...

Why is the PageLoad event triggering repeatedly because of the idletimeout plugin?

We encountered a peculiar problem on an asp.net web form project where the page was loading and displaying data (mainly in a gridview). A strange observation was made when setting a break point in the page load event of a specific page. After about 1-2 min ...

Is Local Storage compatible with phonegap?

I am looking to integrate local storage into my phonegap application in order to store an array of data. Here is a snippet of my code: <div data-role="collapsibleset"> <div data-role="collapsible"> <h3>LOG ...

Implementing URL routing and error handling in a Node.js application using the Express framework

As a newcomer to node.js, I appreciate your patience. I've been experimenting with node.js and the express module. I had an idea for handling browser requests and now I have a simple question: Is this approach good practice, or is there a better sol ...

Assistance required in designing a unique shape using Three.js

https://i.sstatic.net/pmHP2.png Hello there! I could use some assistance with replicating the 2D shape shown in the image above using three.js. Specifically, I'm encountering some difficulty with incorporating the subtle curvature seen on the inner l ...

Is it possible to add information to the form data object?

When I send an image to the server using form data, everything seems fine until I try to add data from a crop plugin. Here is the code snippet: //create form data from form var formData = new FormData($('#my-form')[0]); //append the image formD ...