Search code examples
javascriptarraysnode.jsmongoosesubdocument

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. 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.


Solution

  • 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. 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. 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.

    Thank you Laurentiu & Federico for looking at this and providing some helpful information. sorry about any headaches this may have caused you.