我想根據 URL 從我的 MongoDB 資料庫中獲取資料。如果我訪問 localhost:3000/phones 它應該使用類別電話獲取所有資料,如果它是 localhost:3000/laptops 它應該獲取所有筆記本電腦。
以下是我的架構:
name: {
required: true,
type: String
},
category: {
required: true,
type: String
},
以下是我當前版本的方式:
router.get('/getAll', async (req, res) => {
try {
const data = await Model.find();
res.json(data)
}
catch (error) {
res.status(500).json({ message: error.message })
}
})
我試過了,findByID但沒有用。
uj5u.com熱心網友回復:
答案可以在其檔案中很好地找到:- https://www.mongodb.com/docs/drivers/node/current/quick-reference/
router.get('/phones', async (req, res) => {
try {
const data = await Model.find({category: "phones"});
res.json(data)
}
catch (error) {
res.status(500).json({ message: error.message })
}
})
由于電話和筆記本電腦請求使用相同的查詢,您可以通過在請求中使用查詢引數將其重構為在同一端點中處理
url 的格式為:- localhost:3000/getAll?category=phones
router.get('/getAll', async (req, res) => {
try {
const category = req.query.category
const data = await Model.find({category: category});
res.json(data)
}
catch (error) {
res.status(500).json({ message: error.message })
}
})
uj5u.com熱心網友回復:
您應該使用查詢引數 ?category=phones 或 ?category=laptops 發送您的請求
所以你可以從req.query.category.
這就是你要找的:
router.get('/getAll', async (req, res) => {
try {
const category = req.query.category;
const data = await Model.find({
category,
});
res.json(data)
}
catch (error) {
res.status(500).json({ message: error.message })
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/528256.html
