為什么每當我嘗試這段代碼時都會出錯?
router.get("/", async (req, res) => {
const shopId = req.params.id;
const shopName = req.params.shopName;
try {
const shop = shopId
? await Shop.findById(shopId)
: await Shop.findOne({ shopName: shopName });
const { updatedAt, ...others } = shop._doc;
res.status(200).json(others);
} catch (err) {
res.status(500).json("Shop not found!");
}
});
我只是想獲取存盤在 mongodb 集合中的商店資料。
每當我在 Postman 上嘗試時,我都會收到此錯誤。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /shops/Asos</pre>
</body>
</html>
我不知道我在這里錯過了什么!或者還有其他方法可以實作嗎?通過店鋪名稱或Id獲取資料
uj5u.com熱心網友回復:
const mongoose = require("mongoose");
router.get("/:id", async (req, res) => {
const shopIdOrName = req.params.id;
var shop;
try {
// check if its valid id, else its name
if(mongoose.isValidObjectId(shopIdOrName ){
shop = await Shop.findById(shopIdOrName )
} else {
shop = await Shop.findOne({ shopName: shopIdOrName });
}
const { updatedAt, ...others } = shop._doc;
res.status(200).json(others);
} catch (err) {
res.status(500).json("Shop not found!");
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/537325.html
標籤:节点.js反应
上一篇:如何將指標轉換為多維切片/陣列
