I am trying to delete a 'category' document and it's ObjectId that is in an array inside the 'menu' Schema. The 'menu' Schema looks like this :
categories: [
{
type: ObjectId,
ref: "Category",
},
it holds the ObjectId i am trying to delete
This is the nodejs code from the controller I try to run :
const deletedCat = await Category.findByIdAndRemove(catId, function (err) {
if (err) console.error(err)
})
const updateMenu = await Menu.findOneAndUpdate(
{ _id: menuId },
{ $pull: { categories: { _id: new ObjectId(catId) } } },
{ new: true }
)
the $pull doesn't change the DB and the ObjectId is still in the Array.
I also tried without the " new ObjectId "
What am I doing wrong ?
Ok, so i just got it to work. The answer is simple, just use the ObjectId as a value of the key in the Array (name of the array)
const updateMenu = await Menu.findOneAndUpdate(
{ _id: menuId },
{ $pull: { categories: ObjectId(catId) } },
{ new: true }
)