從我的 MongoDB 資料庫中,我正在查詢資料。為此,在我的后端,我通過這個獲取資料,
const products = await Product.find({
'backCamera.sensor.megaPixels': { $gte: 8 }
})
如何從前端發送 GET 請求來滿足此查詢?
我試過這種方式但沒有用
fetch('http://localhost:5000/api/v1/products?backCamera.sensor.megaPixels[gte]=8')
.then(response => response.json())
.then(data => console.log(data));
然后嘗試在后端使用查詢引數但沒有成功。
uj5u.com熱心網友回復:
首先,你不需要從 URL 中匹配查詢到后端的查詢,也不需要直接發送。因此,你不需要理由去做類似的事情api/v1/products?backCamera.sensor.megaPixels[gte]=8。在這種情況下,我會傳遞類似的東西api/v1/products?backCamSensorMinPx=8,然后我會從 req.query 中提取后端的資料并驗證它。它將解決一些安全問題(如果您使用的是 SQL),并且它將遵循一些將后端核心邏輯和資料庫實作分離的良好實踐。
uj5u.com熱心網友回復:
如果你想用 url 動態地完成整個事情,這意味著引數backCamera.sensor.megaPixels是動態的,你可以這樣去做:
// 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 }
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/379601.html
標籤:javascript 数据库 MongoDB 休息 猫鼬
上一篇:React從類中獲取值
下一篇:如何瀏覽串列
