skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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
            }
          }
        }
      )
    }
    

  2. You don’t need to delete but update using $pull because you are updating the array (removing the object).

    So you can try something like this

    yourModel.update({
      "iqc._id": req.params.id
    },
    {
      "$pull": {
        "iqc": {
          "_id": req.params.id
        }
      }
    })
    

    Example here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search