0

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 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.