[英]How to get the item and remove by id in Express from MongoDB database
我正在構建一個應用程序,其中包括前端的 React、后端的 Express 和 Node,以及作為數據庫的 MongoDB。 我想通過將 id 傳遞給 router.delete function 來刪除任何項目。 我的 function 是這樣的:
const ObjectID = require("mongodb").ObjectID;
router.delete("/:id", auth, (req, res) => {
var id = ObjectID(req.params._id);
console.log(id);
Item.findById(id)
.then(item => {
item.remove().then(() => res.json({ success: true }));
})
.catch(err => {
console.log(err);
res.status(404).json({ success: false });
});
});
當我 console.log(id) 它得到正確的 id 作為“5asta34112daw”之類的東西。 但在控制台上,路線看起來像:
/api/items/[對象對象]
並給出 404。它說刪除 function 返回null
似乎它正在進入 .then 方法但找不到該項目。 有誰能夠幫我? 我的 model 架構是:
const ItemSchema = new Schema({
name: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
},
handler:{
type:String,
required:true
}
});
module.exports = Item = mongoose.model("item", ItemSchema);
您應該為 remove 方法提供一些過濾器。 像刪除({_id:id})。
下面的代碼使用 deleteOne 應該希望對你有用
router.delete("/:id", auth, (req, res) => {
var id = ObjectID(req.params._id);
Item.deleteOne({_id: id})
.then(() => res.json({ success: true }))
.catch(err => {
console.log(err);
res.status(404).json({ success: false });
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.