我還是 Node JS 的新手。我正在嘗試使用 Node JS 和 Mongo DB 創建一個書籍目錄。每次我按洗掉按鈕洗掉一本書時,它都會向我顯示此錯誤
CastError: Cast to ObjectId failed for value "undefined" (type string) at path "_id" for model
"Task"
BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters
這是我的server.js:
app.delete("/api/books/:id", async (req, res) => {
try {
const { id: id } = req.params;
console.log(id);
const task = await Task.findOneAndDelete({ _id: id });
if (!task) {
return res.status(404).json({ msg: `No task with id :${id}` });
}
res.status(200).json(task);
} catch (error) {
console.log(error);
}
});
uj5u.com熱心網友回復:
我也遇到過這個問題。我收到此錯誤是因為通過引數傳入的 ObjectId 在我的資料庫中不存在。因此,這引發了例外。
解決方法:
//add this line as a check to validate if object id exists in the database or not
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).json({ msg: `No task with id :${id}` });
更新代碼:
app.delete("/api/books/:id", async (req, res) => {
try {
const { id: id } = req.params;
console.log(id);
if (!mongoose.Types.ObjectId.isValid(id))
return res.status(404).json({ msg: `No task with id :${id}`
});
const task = await Task.findOneAndDelete({ _id: id });
res.status(200).json(task);
} catch (error) {
console.log(error);
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/447316.html
上一篇:MongoDB/Mongoose,A有很多B,B有很多C,找到所有間接屬于A的C
下一篇:MongooseServerSelectionError:connectECONNREFUSED::1:27017但是我的mongod服務正在運行
