I am trying to delete object from an array. If the object value match that object will be deleted from the database. Here is my database example:
[{
_id: "621773f39ec6fe3a3728d686",
label: "size",
slug: "size",
vendor: "admin",
options: [
{
label: "M",
value: "M"
},
{
label: "XXL",
value: "XXL"
},
{
label: "XL",
value: "XL"
},
{
label: "S",
value: "S"
}
]
}
]
This is my code:
// DELETE FILED FROM ATTRIBUTE
app.put('/dashboard/attribute/fieldDelete/:id', async (req, res) => {
const id = req.params.id
const { value } = req.body
unityMartAttributes.updateOne({ value: value }, { $pull: { options: { _id: objectId(id) } } })
})
Expected output: value: "M" matched that's why that object removed
[{
_id: "621773f39ec6fe3a3728d686",
label: "size",
slug: "size",
vendor: "admin",
options: [
{
label: "XXL",
value: "XXL"
},
{
label: "XL",
value: "XL"
},
{
label: "S",
value: "S"
}
]
}
]
CodePudding user response:
You can do it like this:
app.put('/dashboard/attribute/fieldDelete/:id', async (req, res) => {
const id = req.params.id
const { value } = req.body
await unityMartAttributes.updateOne({ "_id": id }, {
"$pull": {
"options": {
"value": value
}
}
});
}