0

I am trying to remove keywords with Nodejs and Express from a mongoose document that looks somewhat like this:

{
name: "Instagram",
description: "Image sharing website",
keywords: [{name:"Image", value: 1}, {name:"sharing", value: 1}, {name:"website"}, {name:"Instagram", value:5}, {name:"application", value: 2}]
}

Here is the part of my update query which seems to the problem (it does not delete the keywords properly if there are many keywords, though it has worked a couple of times with few keywords):

Model.findOne({_id:req.body.id}, function(err,doc){
    for(var i = 0; i < doc.keywords.length; i++){
       if(doc.keywords[i].value == 1){
          doc.keywords.splice(doc.keywords[i], 1); //does nothing
          doc.save()
          console.log(doc.keywords[i]) //Shows the correct keywords to be deleted.
       }
    };
})
Isaac Krementsov
  • 646
  • 2
  • 12
  • 28

1 Answers1

0

Splice doesn't work on an array of objects. See Remove Object from Array using JavaScript for optional solutions to that. Otherwise I'd suggest a different method, why don't you just filter the keywords based on your needs like:

doc.keywords = doc.keywords.filter((key) => key.value === 1);
Bence Gedai
  • 1,461
  • 2
  • 13
  • 25
  • The reason I don't do that is because I am updating the description of the object, and the object's description is made into keywords, meaning the old description keywords need to be replaced. – Isaac Krementsov Dec 27 '17 at 22:47
  • Then use keywords.map? Your sample suggests, you want to remove some items from the keywords array. – Bence Gedai Dec 27 '17 at 22:50
  • map is not useful in this case. I need to find an element in the array and delete it, which does not work properly. However, the object array removal answers you linked say that I can use .splice(). Is this not working in my case because of node.js or mongoose? – Isaac Krementsov Dec 27 '17 at 22:57
  • Sorry, I misunderstood what you were suggesting. The filtering does work. Thanks! – Isaac Krementsov Dec 27 '17 at 23:07