简体   繁体   English

带有嵌套查询的 GET 请求 REST API

[英]GET request with nested query REST API

From my MongoDB database, I am querying data.从我的 MongoDB 数据库中,我正在查询数据。 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?如何从前端发送 GET 请求来满足此查询?

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.然后尝试在后端使用查询参数,但没有成功。

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.首先,不需要将URL的查询匹配到后端的查询,也不需要直接发送。 Hence, you do not need a reason to do something like api/v1/products?backCamera.sensor.megaPixels[gte]=8 .因此,您不需要理由去做类似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.在这种情况下,我会传递类似api/v1/products?backCamSensorMinPx=8的东西,然后我会从 req.query 中提取后端的数据并对其进行验证。 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.它将解决一些安全问题(如果您使用 SQL),它将遵循一些分离后端核心逻辑和数据库实现的良好实践。

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:如果你想用 url 动态地完成整个事情,这意味着参数backCamera.sensor.megaPixels是动态的,你可以像这样使用 go :

// 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 }
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM