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
I figured it out. This should be working in NodeJS. No problemo.
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
Example here