Home > Mobile >  How to delete an element of an array using mongoose
How to delete an element of an array using mongoose

Time:01-26

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!

CodePudding user response:

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.

  •  Tags:  
  • Related