What is the best way to update the key for the sorting field in a meteor collection query?

I am struggling to replace the name key with a value passed in via a parameter this.params.sortby in the code below. Any help would be appreciated.

For example, if:

this.params.sortby=location

I would like the following:

Template.MyTemplate.helpers({
    data: function () {
      return MyCollection.find({},{sort:{name: 1 }});
    }
  });

To be changed to this:

Template.MyTemplate.helpers({
    data: function () {
      return MyCollection.find({},{sort:{location: 1 }});
    }
  });

Answer №1

If you need to dynamically name keys in an object, you can achieve this using the bracket notation. Here's an example:

var dynamicObject = {};
dynamicObject[this.userInput.dynamicKey] = 'some value';

For instance, if this.userInput.dynamicKey is set to "category", your dynamicObject will look like this:

var dynamicObject = {
  category: 'some value'
};

You can then use this object to sort your data accordingly:

MyData.find({}, {sort: dynamicObject});

Answer №2

Create a specialized SORT factory constructor to produce sorting standards prior to executing the query.

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 something incorrect with the incrementation in JavaScript?

for (let i = 0; i < 5; ++i){ alert(i); } for (let i = 0; i < 5; i++){ alert(i); } Both of these constructs get the same result: 0, 1, 2, 3, 4. But what are the underlying differences between them? And does the choice of increment in a for l ...

Is it possible for a destructed assignment to yield multiple objects?

I am faced with a collection of Storybook stories and a function that produces a ComponentStory object. I am aiming to find a concise method for duplicating multiple stories without resorting to repetitive code like this: export const Default = bindStory(T ...

What is the most effective way to iterate through an array of objects and retrieve the results in a key-value format?

I am dealing with an array of objects that may seem a bit complex initially, but I will simplify it as much as possible. Each object in the array has properties like Engineering, Environment, and others, each containing a sub-object called radars. The rada ...

Learn how to create a button that will only submit a value when clicked using Node.js and EJS

Currently in my ejs file, I have a button that sends a value to app.js instantly when the program runs. However, I want it to only submit the value when clicked by the user. <% notesArray.forEach((note,i) =>{ %> <div class="note"> ...

Is there a difference between innerHTML strings and their corresponding strings in JavaScript?

I am facing an issue with a code snippet that seems to have an unusual error. The following code is a simplified version to demonstrate the strange behavior. <html> <head> <script type = "text/javascript"> window.onload = fun ...

Issue with the secondary mongoose Model functionality not operational

I am currently developing an API using Node.js, Express, and MongoDB. Below is the code for my api.js file: var express = require('express'), mongoose = require('mongoose'); var app = module.exports = express(); mongoose.connect ...

Updating React markers dynamically on Google Maps issue

I'm currently developing a transportation app with React and the @react-google-maps/api library. The app includes a map component that displays the real-time location of delivery workers using custom icons. However, I've encountered an issue wher ...

Is there a way to deactivate the checkbox in an AngularJS input field?

<div ng-repeat="x in spaceutilization"> <input type="checkbox" name="{{x.filenumber}}" id="{{x.id}}" class = "pdffiles" value="101SP{{x.initials}}.dwg" /><label for="{{x.id}}"><button type = "button" class = "btn btn-primary btn-sm h ...

How to store an imported JSON file in a variable using TypeScript

I am facing a challenge with a JSON file that stores crucial data in the following format { "login": { "email": "Email", "firstName": "First name", "lastName": "Last name", ...

Unable to use the res.send() function

I've been working on a Node.js project. Within the validate.js file, I have defined a class Validate with a static method validateTicket and exported the class at the end. validate.js file const request = require("request"); const config = { urlBas ...

The issue of Mongoose not populating a virtual field with a getter function remains unresolved

While trying to populate a virtual field in a mongoose schema using a getter function, I encountered an error. The error message reads: MongooseError: If you are populating a virtual, you must set the localField and foreignField options It seems that whe ...

Storing query for later utilization using form and javascript

I have implemented a function to create charts using the following code snippet: $('#button_submit').click(function() { var start_date = $('#start_date').val(); var end_date = $('#end_date').val(); var type = $( ...

Vue.JS enables the seamless addition of rows to a form on the fly

I am currently working on creating a dynamic form using Vue. The concept is that when the user clicks the add button, another row will appear for them to input data. However, I encountered an issue where initially only 1 row was set up, but when I added th ...

Handling a substantial array containing over 12,000 rows in JavaScript

The criteria for this project are unique, but I am seeking some perspective... I possess a CSV file filled with 12,000 rows of data distributed across 12-15 columns. My objective is to convert this into a JSON array and load it using JSONP (must be execut ...

What is the method for creating a MongoDB collection index that enforces uniqueness in a case-insensitive manner?

When designing a user schema, I require usernames to be case insensitive, ensuring no two usernames are similar even when taking into account capital letters. To achieve this, I initially added collation with a locale of 'en' and a strength of 2 ...

Tried to enroll the RCTBridgeModule category as RCTFileReaderModule

Trying to register the RCTBridgeModule class RCTFileReaderModule with the name 'FileReaderModule' failed because the name was already taken by the FileReaderModule class. This issue arises when attempting to launch an application on iOS using th ...

How can we optimize axios requests with lodash debounce?

Utilizing a state prop named network busy status to control elements in the UI. Due to the rapid changes in status, my spinner appears overly active. Is there a simple method, utilizing lodash _.debounce, to throttle this section of code? const instance ...

How can I incorporate Bootstrap multi-select into the jQuery DataTables DOM?

Having trouble implementing a bootstrap multi-select inside a jQuery datatable DOM. I followed this example to add a custom element within the jQuery datatable container. It works fine for normal bootstrap select, but when trying to add a bootstrap multi-s ...

Challenging glitch in the JavaScript code

My jQuery code seems to be functioning properly in online text editors like Fiddle and StackOverflow snippets. However, when I try to implement the same code in Brackets or view it on GitHub, the navbar scroll down animation fails to work as expected. You ...

Using AngularJS to serve $resource through https causes Angular to transition from https to http

After successfully setting up a ng-resource in my AngularJS project to fetch data from a REST API, everything was running smoothly in the development and testing environments, both of which operated over http. However, upon moving to production where the e ...