0

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.

Smiggez
  • 21
  • 1
  • 7

3 Answers3

0

First, your method requires a objectID. Try like this and see if it works:

Product.findByIdAndRemove(ObjectId(req.params.product_id)
Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
  • Thank you for this information. I added it, but received the following error when I tried it out: ReferenceError: ObjectId is not defined – Smiggez Jul 24 '18 at 17:16
  • Tried the edited version and got the same message: ReferenceError: objectID is not defined – Smiggez Jul 24 '18 at 18:13
  • First require the ObjectId function var ObjectId = require('mongodb').ObjectID; – Laurentiu Enache Jul 24 '18 at 18:27
  • Or instead try : Product.findByIdAndRemove(ObjectId({"_id": req.params.product_id}) – Laurentiu Enache Jul 24 '18 at 18:30
  • Ended up using: var ObjectId = require('mongodb').ObjectId; Product.findByIdAndRemove(ObjectId(req.params.product_id), function(err) ---- It deleted the Product from the products collection/table, but it the information is still in the array. – Smiggez Jul 24 '18 at 20:01
  • Hmm... what array? You say the product is succesfully deleted from db now? ok – Laurentiu Enache Jul 25 '18 at 00:42
  • So in the Product collection, it's removed, but I think I pushed the product in the client.products[{}]. So it's still in the clients.products[{The same data that was in Product collection}] --- I hope this makes sense sorry. – Smiggez Jul 25 '18 at 01:56
0

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.

Smiggez
  • 21
  • 1
  • 7
0

Looked into documents and it won't delete. It deletes the content not the ID, so it stays in the MongoDB Database.

enter image description here

 router.delete('/inventario/:_id', function(req, res){
      Propiedades.findByIdAndDelete(req.params._id, function(err,){
         if (err){
             res.redirect('/inventario/');
         } else {
             res.redirect('/inventario/');
       }
    })
 });
Angel F Syrus
  • 1,984
  • 8
  • 23
  • 43