node.jsmongodbexpressnestedhttp-delete

How to delete an object in nested array of objects in MongoDB with node js


I'm still a beginner in node express js and mongoDB. Right now, I'm trying to Delete an object in nested array of objects.

Array of Objects:

[{
  _id: new ObjectId("63d89f8823981819cf61816e"),
  iqc: [
    {
      partname: 'jio',
      vendorname: 'jio',
      partcode: '1234',
      grndate: '2023-01-10',
      project: 'jio',
      lotqty: '200',
      failurerate: '15%',
      issuedetails: 'damaged',
      status: 'pending',
      _id: new ObjectId("63d89f8823981819cf61816f")
    },
    {
      partname: 'sky',
      vendorname: 'sky',
      partcode: '5678',
      grndate: '2023-01-04',
      project: 'sky',
      lotqty: '300',
      failurerate: '20%',
      issuedetails: 'damaged',
      status: 'pending',
      _id: new ObjectId("63d89f8823981819cf618170")
    }
  ],
  __v: 0
}]

I want to delete the object in iqc which has the _id: new ObjectId("63d89f8823981819cf618170").

So i tried this code for deleting in node js. It didnt work.It throws an error data.iqc.findByIdandDelete is not a function

app.delete('/delete/:id/:secondid', async (req, res) => {
    const data = await IQC.findById(req.params.id);

if(data )
    {
        await data.iqc.findByIdandDelete(req.params.secondid)
        return res.json("Deleted  Successfully")
    }

});

Here IQC is the db collection and secondid is the id of the nested object id which I wanted to delete _id: new ObjectId("63d89f8823981819cf618170").

Thanks in Advance.


Solution

  • I figured it out. This should be working in NodeJS. No problemo.

    app.delete('/delete/:id/:secondid', async (req, res) => {
      await IQC.findOneAndUpdate(
        {
          _id: req.params.id
        }, {
          $pull: {
            iqc: {
              _id: req.params.secondid
            }
          }
        }
      )
    }