简体   繁体   English

Node.js/mongoose - 数组中的子文档不会删除/移除

[英]Node.js/mongoose - sub-document in a array won't delete/remove

So this is my first on-my-own node.js project after finishing up an online Bootcamp.所以这是我完成在线训练营后的第一个我自己的 node.js 项目。 Running into trouble removing a sub-doc in my array.在我的阵列中删除子文档时遇到问题。 Here's some code, I hope I provide enough info for someone to help me out.这是一些代码,我希望我提供足够的信息让有人帮助我。

models:
var productSchema = new mongoose.Schema({
    name: String,
    type: String,
    location: String 
});

var clientSchema = new mongoose.Schema({
    name: String,
    address: String,
    contactinfo: String,
    products:[]    
});

And this is my post route that is adding the product to the client, which works great:这是我将产品添加到客户端的发布路线,效果很好:

//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');
                  } 
            });
     });
});

My delete route is my problem child.我的删除路线是我的问题孩子。 It deletes the product, but I can't seem to get it out of the array at all.它删除了产品,但我似乎根本无法将其从数组中删除。 I did some research and tried the following:我做了一些研究并尝试了以下方法:

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

I get errors or it deletes the client,我收到错误或删除客户端,
but never deletes the product from the array.但永远不会从数组中删除产品。 Any help would be great or if there's a better way to do this, that would be great too.任何帮助都会很棒,或者如果有更好的方法来做到这一点,那也很棒。 Tried for a week before turning for help, so open for feedback from skilled developers.在寻求帮助之前尝试了一周,因此请开放来自熟练开发人员的反馈。

oh here is my last delete route, think I'm going to disable until I found a fix , so I can continue my project.哦,这是我最后的删除路线,我想在找到修复之前我会禁用,这样我就可以继续我的项目。

//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/");
        });
    }
});

}); });

The length I used to see if anything changed and it never did.我过去常常查看是否有任何变化的长度,但它从未发生过。

First, your method requires a objectID .首先,您的方法需要一个objectID Try like this and see if it works:像这样尝试,看看它是否有效:

Product.findByIdAndRemove(ObjectId(req.params.product_id)

Nevermind, it seems that the issue here is my code.没关系,这里的问题似乎是我的代码。 Instead of pushing a ref in my client schema for the products array I pushed the product info directly in the array.我没有在我的客户端架构中为 products 数组推送 ref,而是直接在数组中推送了产品信息。 Then in my app in one area I'm accessing the data from the Product collection, but in another part of my app I'm accessing the same info from the client collection through the products array.然后在我的应用程序的一个区域中,我正在访问 Product 集合中的数据,但在我的应用程序的另一部分中,我正在通过 products 数组访问来自客户端集合的相同信息。 Based on my training(Other course apps I created) it seems that the ref doesn't get remove it just can't refer to the collection since it's no longer in the collection.根据我的培训(我创建的其他课程应用程序),似乎 ref 没有被删除它只是无法引用集合,因为它不再在集合中。

Thank you Laurentiu & Federico for looking at this and providing some helpful information.感谢 Laurentiu 和 Federico 看到这个并提供了一些有用的信息。 sorry about any headaches this may have caused you.对于这可能给您造成的任何头痛,我们深表歉意。

Looked into documents and it won't delete.查看文档,它不会删除。 It deletes the content not the ID, so it stays in the MongoDB Database.它删除的是内容而不是 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM