0
CustomItemCollection.find({name: urlPath}, function(err, data){
      if(err){
        console.log(err);
      }
      else{
        let returnedData = data[0].item;
        for(var i = 0; i < returnedData.length; i++){
          if(returnedData[i]._id === checkboxButton){
            //delete this object nested inside the array
          }
        }
      }
    })

Im trying to delete an element inside an array. I tried following some other posts on here but they didn't work. Can someone tell me how to do this? Here's the schema if that'll help:

const CustomItemSchema = {
  name: {
    type: String,
    required: 1,
    unique: 1
  },
  item: [{
    myItems: String
  }]
}

i wanna delete one of the "myItems" created using its id. I have gotten its id but i don't know how to delete it.

Thanks for your help!

1 Answer 1

0

If I've understood correctly you only need to use $pull like this:

CustomItemCollection.updateOne(
{
  "name": urlPath
},
{
  "$pull": {
    "item": {
      "_id": checkboxButton
    }
  }
})

Example here

Note that I've used updateOne but you can use other query as findOneAndUpdate or updateMany if you need.

2
  • Thank you very much, this worked perfectly!
    – Git Bot
    Jan 25, 2022 at 3:45
  • You are welcome. Also if the issue has been solved, mark the answer as accepted is appreciated.
    – J.F.
    Jan 25, 2022 at 8:04

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.