From my MongoDB database, I am querying data. For this, in my backend, I am getting the data by this,
const products = await Product.find({
'backCamera.sensor.megaPixels': { $gte: 8 }
})
How I can send a GET request from the front end to meet this query?
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));
Then tried to use the query params in backend but didn't work out.
CodePudding user response:
First of all, you do not need to match the query from the URL to the query in the backend, nor to send it directly. Hence, you do not need a reason to do something like api/v1/products?backCamera.sensor.megaPixels[gte]=8
. In this case, I would pass something like api/v1/products?backCamSensorMinPx=8
, and then I would extract the data on the backend from req.query and validate it. It will solve some security issues (in case you were using the SQL), and it will follow some good practices of separating the backend core logic, and the database implementation.
CodePudding user response:
If you want the entire thing dynamically with the url, meaning that the parameter backCamera.sensor.megaPixels
is dynamically, you can go for it like this:
// Frontend
fetch('http://localhost:5000/api/v1/products?product=backCamera.sensor.megaPixels&minimum=8')
.then(response => response.json())
.then(data => console.log(data));
// Backend
// Retrieve the params product and minimum from the Url
const products = await Product.find({
[product]: { $gte: minimum }
})