希望你能在這里幫助我。我將 json 存盤在 mongodb 中。該 json 包含有關手機的資料,例如型號、價格、img src。獲得帶有引數(例如 url 中的價格)的 GET 請求后,我想將其與存盤在 db 中的資料進行比較,并僅回傳包含此類結果的物件。下面提供我當前的代碼(其中 Phone 是 mongoose.model 的名稱):
router.get("/:price", async (req, res) => {
try {
const phone = await Phone.find(c => c.price === parseInt(req.params.price));
if (!phone) res.status(404).send('The phone with the given price was not found');
res.send(phone);
} catch (e) {
res.send('Error ' e);
}
})
我不得不提到代碼的其余部分在普通的 get、post 請求上沒有問題。所以我想這個問題隱藏在這部分代碼中。我在控制臺中遇到的錯誤: node:events:368 throw er; // 未處理的“錯誤”事件 ^
型別錯誤:無法讀取 null 的屬性(讀取“價格”)。在 Postman 中,我還有另一個:MongooseError: Query was already execution: Phone.find({})
uj5u.com熱心網友回復:
我認為您將 JSArray.find()方法與 MongoDBfind({})方法混淆了。改變你的find方法是這樣的:
Phone.find({ "price": parseInt(req.params.price) });
假設您price的Phone模型中有該屬性,這將找到price等于的所有檔案req.params.price
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364408.html
