[英]Node.js/mongoose - sub-document in a array won't delete/remove
所以這是我完成在線訓練營后的第一個我自己的 node.js 項目。 在我的陣列中刪除子文檔時遇到問題。 這是一些代碼,我希望我提供足夠的信息讓有人幫助我。
models:
var productSchema = new mongoose.Schema({
name: String,
type: String,
location: String
});
var clientSchema = new mongoose.Schema({
name: String,
address: String,
contactinfo: String,
products:[]
});
這是我將產品添加到客戶端的發布路線,效果很好:
//Add New Product
app.post("/clients/:id/products", middleware.isLoggedIn, function(req, res){
Client.findById(req.params.id, function(err, client) {
if(err){
console.log(err);
req.flash('error', "We cannot find the Client!!!");
return res.redirect("/clients/" + req.params.id + "/products/new");
}
Product.create(req.body.product, function(err, product){
if(err){
req.flash('error', "There was an error adding the product to the user, try again");
} else{
client.products.push(product);
client.save();
req.flash('success', "You have added a New Product");
res.redirect('/clients/' + req.params.id +'/products/new');
}
});
});
});
我的刪除路線是我的問題孩子。 它刪除了產品,但我似乎根本無法將其從數組中刪除。 我做了一些研究並嘗試了以下方法:
client.products.find({_id:req.params.product_id}).remove()
client.products.id(req.params.product_id).remove()
client.products.pull({_id: req.params.product_id})
client.find({products:{_id: req.params.product_id}}).remove()
using client.save() right after each
我收到錯誤或刪除客戶端,
但永遠不會從數組中刪除產品。 任何幫助都會很棒,或者如果有更好的方法來做到這一點,那也很棒。 在尋求幫助之前嘗試了一周,因此請開放來自熟練開發人員的反饋。
哦,這是我最后的刪除路線,我想在找到修復之前我會禁用,這樣我就可以繼續我的項目。
//Delete a Product
app.delete("/clients/:id/products/:product_id", middleware.isLoggedIn, function(req, res){
Product.findByIdAndRemove(req.params.product_id, function(err){
if(err){
console.log(err);
} else {
console.log("Should be deleted now!");
Client.findById(req.params.id, function(err, client) {
if(err){
console.log(err);
}
console.log(client.products.length);
client.find({products: {_id: req.params.product_id}}).remove();
client.save();
console.log(client.products.length);
res.redirect("/clients/");
});
}
});
});
我過去常常查看是否有任何變化的長度,但它從未發生過。
首先,您的方法需要一個objectID
。 像這樣嘗試,看看它是否有效:
Product.findByIdAndRemove(ObjectId(req.params.product_id)
沒關系,這里的問題似乎是我的代碼。 我沒有在我的客戶端架構中為 products 數組推送 ref,而是直接在數組中推送了產品信息。 然后在我的應用程序的一個區域中,我正在訪問 Product 集合中的數據,但在我的應用程序的另一部分中,我正在通過 products 數組訪問來自客戶端集合的相同信息。 根據我的培訓(我創建的其他課程應用程序),似乎 ref 沒有被刪除它只是無法引用集合,因為它不再在集合中。
感謝 Laurentiu 和 Federico 看到這個並提供了一些有用的信息。 對於這可能給您造成的任何頭痛,我們深表歉意。
查看文檔,它不會刪除。 它刪除的是內容而不是 ID,因此它保留在 MongoDB 數據庫中。
router.delete('/inventario/:_id', function(req, res){
Propiedades.findByIdAndDelete(req.params._id, function(err,){
if (err){
res.redirect('/inventario/');
} else {
res.redirect('/inventario/');
}
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.