What is the method for sorting in MongoDB using the objects in the URL query string?

How can I sort a MongoDB collection in a Node.js application based on the query string provided in the URL?
The URL looks like this: http://localhost:5000/v1/bid/sort_bid?sort={"_id": -1,"enquiry_no": 1}

I am trying to pass an object in the code below:

const getSortedBidList = catchAsync(async (req, res) => {
    let { sort } = req?.query;
    console.log('Query String', sort);
    let object = new Object();
    object[sort] === 1 ? 'ASC' : 'DESC';

    let result = await Bid
        .find({})
        .sort(object)
        .limit(limit)
        .skip(offset);

} I have tried passing the query string object in the sort method, but it is not working as expected. Any help or suggestions would be greatly appreciated. Thank You

Answer №1

Consider the following steps:

http://localhost:5000/v1/bid/sort_bid?sort[_id]=-1&sort[enquiry_no]=1

For a deeper understanding of how express handles query strings, refer to this resource.

It is advisable to utilize the qs npm package for converting objects into query strings programmatically on the frontend:

import qs from 'qs';

async function sendRequestToBackend(queryAsObject) {
  const stringifiedQuery = qs.stringify(queryAsObject);
  await sendRequest(`http://localhost:5000/v1/bid/sort_bid?${stringifiedQuery}`)
}

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

Invoking an AJAX function that is not inside the document.ready function

I'm having trouble populating a Google Map and here's some of the code I'm using. The ajax request doesn't seem to be working properly. When I put everything inside document.ready() as an anonymous function, it works fine. However, sinc ...

The `stream.Transform.unshift()` method in Node.js

Let's take a look at this simple example: stream = require 'stream' util = require 'util' class TestTransform extends stream.Transform _transform: (chunk, encoding, callback) -> if not @noMore @noMore ...

What is the procedure for creating a JSON object in Android using Java?

Below is the code snippet I am working with: { "body": "{\"data\": [[1633209578,0,117.000000],[1633209578,1,116.000000],[1633209624,2,121.000000],[1633209643,3,174.000000],[1633209682,4,222.000000],[1633209715,5,247.0 ...

Use hyphens instead of spaces in angular js data binding

<form role="form" method="POST" action="{{ url('/roles/save') }}" data-ng-app=""> <div class="form-group"> <label>Page-Title:</label> <input type="text" required value="" data-ng-model="title" name="pag ...

Interactive Image Component in React

I'm encountering an issue with my React code. import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import RecipeService from "./RecipeService"; import RecipeProfileImg from "./Re ...

The close icon in the ReactStrap modal is not being displayed properly, and I need to know how to utilize the header with a different tag

I recently started working with React JS and I am currently utilizing the Modal component from reactStrap. <Modal isOpen={props.isOpen} centered='true'> <ModalHeader> Change this Question? <button type= ...

Implementing calculation and sorting functionality in Vue.JS for multidimensional JSON objects

I have a complex JSON feed containing various events with multiple dates and locations. Each date for an event includes latitude and longitude, which I use to calculate distance using HTML5 geolocation. My goal is to add this calculated distance to the chi ...

eliminate the script and HTML comment from a designated division

Here is the default code that I need to modify using JavaScript to remove scripts, comments, and some text specifically from this div: I came across this script that removes all scripts, but I only want to remove specific ones from this div: $('scri ...

Ways to apply the strategy pattern in Vue component implementation

Here's the scenario: I possess a Cat, Dog, and Horse, all of which abide by the Animal interface. Compact components exist for each one - DogComponent, CatComponent, and HorseComponent. Query: How can I develop an AnimalComponent that is capable of ...

JQuery Form Wizard - Adding a Finish Button Linked to a Page

Having some difficulty linking the finish button on my Jquery Form Wizard within my Flask App to a link. I attempted to test the functionality by creating a simple alert, but that didn't work either. I'm certain that I missed a step somewhere, b ...

Tips for displaying a modal within a modal in React

Currently, I have two components with modals. My goal is to open one modal from a button in the other component but clicking the button only closes the current active modal and doesn't open a new one. //Modal 1 <div className="modal fade" ...

Discover the hidden truth: Unveiling the enigma of React

I'm currently learning React and I've been working on some apps to enhance my skills and deepen my understanding. Right now, I am facing a challenge where I need to incorporate the logged user information into the Redux state. However, whenever I ...

Efficient database optimization for handling numerous ajax/php requests in PostgreSQL

I'm currently using AJAX and PHP for updating a postgreSQL database. Imagine having 1000 users sending one ajax post request per second to a php script. This would mean that the php script opens a connection, runs two SQL update commands each time, a ...

Challenges with session timeouts during extended long-polling sessions:

I have implemented the following code in a servlet to set the session timeout duration: session.setMaxInactiveInterval(5 * 60); While this approach has been effective, I am now facing an issue where sending polling requests to the server from JavaScript ...

Retrieve information from server using pug script with specified type as 'text/javascript'

I'm currently attempting to fetch data from the server within my pug template. The route I have set up is as follows: app.get('/serverdata', async(req, res) => { const chartData = [] for (const i = 0; i < 7; i++) { chartData ...

What is the best way to locate an element through its parent?

I am working with the following HTML structure: <div class="row" id="row-1"> <div class="row-wrapper"> <div class="cell-1"></div> <div class="cell-2"></div> <div class="cell-3"></div> ...

Using React's useEffect and useContext can cause issues with certain components, particularly when dealing with dynamic routes

Currently, I am developing a React blog application where posts are stored in markdown files along with metadata in Firestore. The content .md files are saved in Cloud Storage. In the App component, I utilize useEffect to retrieve the metadata for each pos ...

Developing a Java application that involves reading from a file, writing to a file,

I'm currently struggling with an assignment and desperately need some assistance. I've made progress but have been stuck for several days now. The task involves students in their first year of a degree program in Irrational Studies, who take two ...

What's preventing me from tapping on hyperlinks on my mobile device?

I'm currently working on a website (saulesinterjerai.lt) and everything seems to be functioning properly, except for the fact that on mobile devices, the links aren't clickable and instead navigates to other layers. How can I disable this behavio ...

RxJS equivalent of a 'finally' callback for Promises

In my component, I have a process that retrieves data from an API. To indicate whether the data is being loaded or not, I use a member variable called loading. Once the data retrieval process is complete, I set loading to false to hide the loading icon. Th ...