Requesting data from a REST API using a nested query in a GET

After querying data from my MongoDB database, I am faced with the challenge of sending a GET request from the front end to meet this specific query. In my backend code, I retrieve the data using the following:

const products = await Product.find({
    'backCamera.sensor.megaPixels': { $gte: 8 }
  })

I attempted to send a GET request in the frontend using the approach below, but unfortunately, it did not yield the expected results:

I've tried this way but didn't work

fetch('http://localhost:5000/api/v1/products?backCamera.sensor.megaPixels[gte]=8')
      .then(response => response.json())
      .then(data => console.log(data));

Furthermore, I also experimented with incorporating query params in the backend, however, I encountered issues that prevented its successful execution.

Answer №1

To begin with, there is no requirement to directly match the query from the URL with the backend or send it as is. This means you don't have to use something like

api/v1/products?backCamera.sensor.megaPixels[gte]=8
. Instead, a more efficient approach would be to pass a simplified version such as
api/v1/products?backCamSensorMinPx=8
, which can then be extracted and validated on the backend using req.query. This method not only addresses potential security vulnerabilities (especially if utilizing SQL), but also adheres to best practices by separating core logic from database implementation.

Answer №2

To retrieve the entire content dynamically using the URL, where the parameter backCamera.sensor.megaPixels is dynamic, you can follow this approach:

// Frontend
fetch('http://localhost:5000/api/v1/products?product=backCamera.sensor.megaPixels&minimum=8')
      .then(response => response.json())
      .then(data => console.log(data));

// Backend
// Extract the parameters product and minimum from the URL
const products = await Product.find({
    [product]: { $gte: minimum }
  })

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

Instead of using colons, display the separation of hours, minutes, and seconds with underscores

Currently, I am utilizing moment.js to retrieve the present date and time with the intention of formatting it in the specific format below 'MMMM Do YYYY, h:mm:ss a' Unfortunately, the problem arises as the delineation between hours, minutes, and ...

``Protect your PDF Document by Embedding it with the Option to Disable Printing, Saving, and

Currently, I am facing a challenge to enable users to view a PDF on a webpage without allowing them to download or print the document. Despite attempting different solutions like Iframe, embed, PDF security settings, and Adobe JavaScript, I have not been s ...

How come my effort to evade quotation marks in JSON isn't successful?

When trying to parse a JSON-string using the JQuery.parseJSON function, I encountered an error message that read: Uncaught SyntaxError: Unexpected token R. This was unusual as the only uppercase 'R' in my JSON-formatted string appeared right afte ...

Ways to add a substantial quantity of HTML to the DOM without relying on AJAX or excessive strings

Currently, I am looking to update a div with a large amount of HTML content when a button on my webpage is clicked. The approach I am currently using involves the .html() method in JQuery, passing in this extensive string: '<div class="container-f ...

Issue with Jquery function not executing on second attempt

/** Creates a table of iTunes data in HTML format **/ var appendValues = function(songArray) { songArray.each(function() { var title = $(this).find("im\\:name").eq(0).text(); var songImage = $(this).find("im\\:image").eq(0).text(); var ...

Display the returned view following an AJAX request

Currently, I am trying to search for a specific date in the database using ajax to trigger the function. However, I am encountering a 404 error when I should be receiving the desired outcome, and the ajax call is entering an error mode. Here is the snippet ...

Rgd: Double-Sided Horizontal Slide Control

While browsing the internet, I came across several examples of horizontal sliders with adjustable values. For example, if I set the maximum value as 100 and move the slider 10 sectors to the left, each sector would decrease by 10. What I am trying to ach ...

React Weather App: difficulties entering specific latitude and longitude for API requests

I have successfully developed an app that displays the eight-day weather forecast for Los Angeles. My next objective is to modify the longitude and latitude in the API request. To achieve this, I added two input fields where users can enter long/lat values ...

I want to display events from my database table on their corresponding dates using JavaScript and jQuery. How can I achieve this?

Using the FullCalendar plugin, I attempted to achieve a specific functionality, but unfortunately fell short of my goal. Below is the snippet of my scripting code: $('#calendar').fullCalendar({ //theme: true, header: { ...

Step-by-step guide on how to activate a colorbox using a targeted Id or class

Below is the code I'm currently working with: <div class="hidden"> <div id="deletePopContent" class="c-popup"> <h2 class="c-popup-header">Delete Practice Sheet</h2> <div class="c-content"> <h3 ...

Angular filter that replaces underscores with spaces

Looking for a solution to replace underscores with spaces in a string ...

Ways to extract a specific element from a webpage's body section

When utilizing node-fetch to retrieve the body of a site, I follow this process: import fetch from 'node-fetch'; (async () => { const response = await fetch('link'); const body = await response.text(); console.log(body) ...

Mongoose 5 unexpectedly encounters the error message "MongoError: unrecognized string alias for $type: 2dsphere"

Everything was running smoothly while I was using Mongoose 4.x. However, once I updated it to Mongoose 5.0.1, a new error started popping up. /Users/me/ExampleCode/example-backend/example-backend-admin/example-backend-admin-places/node_modules/mongoose/li ...

The Docker build encountered an error due to confusion with MERN dependencies

Utilizing the MERN stack, this application is built with ReactJS, Node, and MongoDB. I have successfully created a docker container that runs the frontend, but unfortunately, an error keeps arising which I can't seem to pinpoint. The error message I ...

Understanding the moment when the DOM is fully rendered within a controller

I'm currently facing an issue with AngularJS. In my controller, I have a $watch setup like this: function MyController() { $watch('myModel', function() { $rootScope.$emit('do-oper'); }); } The value of 'myMod ...

Unable to reach 'this' within a nested function

Struggling with a coding issue for hours now and in need of some assistance. The challenge at hand involves creating an object named Rank. Rank is expected to make DB calls in mongodb to retrieve data needed to populate a matrix, followed by executing nes ...

When the properties change, React Router Redux does not get rendered

I am encountering a challenge with using react router redux, where everything seems to be working well except for rendering when props change. Index.js import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} fro ...

Next.js Error: The text displayed on the page differs from the HTML rendered by the server

Currently, I am facing an issue with the error "Error: Text content does not match server-rendered HTML." Here is my scenario - I have received a dateTime from an API, for example '2022-12-25T11:22:37.000Z', and I want to display it on a compone ...

Looking for a versatile jQuery plugin that enables right-click functionality across different browsers?

I am currently using a context menu plugin that displays a context menu when an element is right-clicked. However, this does not work on elements embedded with ajax. To solve this issue, I am considering utilizing ajax live to trigger the context menu func ...

Troubleshooting AWS S3 SDK upload error when sending data from Next.js API endpoint hosted on Vercel - ERR_HTTP_HEADERS_SENT

I'm currently working on uploading a file from my Next.js API endpoint running on Vercel using the @aws-sdk/client-s3 package. Here's a snippet of my code: import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3"; import type { N ...