Search code examples
node.jsmongoose

deleting item from array using mongoose in Nodejs


I am making a to-do list app. I want to delete one item from an array, but using Model.findOneAndUpdate() it is not working. Please help me if I am making a mistake in syntax, or you can suggest another way.

app.post("/delete", function(req,res){
  
  const checkedItemId = req.body.checkbox.trim();
  const listName = req.body.nameOfItemToDelete;

  if (listName==="Today"){
    Item.findOneAndDelete(checkedItemId)
      .then(function (item) {
        res.redirect("/")
        console.log("item is deleted")
      })
      .catch(function (err) {
        res.redirect("/")
        console.log("err while deleting")
      })
  }
  else{
    
    List.findOneAndUpdate({ name: listName }, { $pull: { items: { _id:  checkedItemId  } } })
      .then(function(foundlist){
        res.redirect("/"+listName)
      })
  }
  
})

Please review the code and if possible then help me


Solution

  • Try:

    List.findOneAndUpdate({ name: listName }, { item: { _id:  checkedItemId  } })
      .then(function(foundlist){
        res.redirect("/"+listName)
      })
    

    Based on your comments, you need to ensure that your List schema has a reference to your Item schema sub-documents as suggested in the docs like so:

    const listSchema = new Schema({
       name: {
          type: String,
          required: true
       },
       items: [{
          type: mongoose.ObjectId,
          ref: 'Item'
       }]
    });
    

    This way each item is a sub-document and the List contains an array of all the relevant ObjectId related to that list. This is the best way to handle references between two documents. Otherwise your items is just an array of strings and you will need to use traditional search techniques to pull items from an array (select by index, using loops or array.find() etc) which are not as optimised as sub-documents.