Jackmc1047 Jackmc1047 - 28 days ago 25
Node.js Question

How do you find and remove a Mongoose subdocument within an array by its id?

I have the following mongoose schema:

{
name: String,
subArray: [
{
subName: String,
subNumber: Number
}
]
}


I've added objects to the subArray, which get automatically assigned an
"_id"
. In Node.js, how do I find an object by
"_id"
within the subArray and remove it?

Answer

You can se mongoose findOneAndUpdate along with $pull operator. So something like following would work (untested):

Model.findOneAndUpdate( {'subArray._id' : '55a19992474e7ded6b4ae2b0'} ,
  {
    $pull: { subArray: { _id: '55a19992474e7ded6b4ae2b0' }}
  }
  {new: true},
  function(err, doc){
     console.log(err,doc)
})