【发布时间】:2019-01-01 08:47:47
【问题描述】:
所以这是我完成在线训练营后的第一个我自己的 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/");
});
}
});
});
我用来查看是否有任何改变但从未改变的长度。
【问题讨论】:
标签: javascript arrays node.js mongoose subdocument