I have two related objects a menu and menu items. Menus do not know about their menu items. Menu items contain an array of references to menus that they are a part of. My schema looks like this:
let MenuItemSchema = new Schema({
//other fields
current_menus: [{ type: Schema.Types.ObjectId, ref: "Menu" }],
});
I am trying to delete the menu reference from its menu items when I delete a menu object. This is my current code in my menu router:
router.get("/delete/:id", async function (req, res) {
let thisMenu = await Menu.findById(req.params.id).exec();
let allMenuItems = await thisMenu.menu_items; //Menu has a virtual function called
"menu_items" that returns all the menu
items that contain a reference to the
current menu
for (let menuItem of allMenuItems) {
MenuItem.findByIdAndUpdate(
menuItem._id,
{ $pull: { 'current_menus': { _id : thisMenu._id } } },function(err,model){
if(err){
console.log(err);
}
console.log(menuItem);
});
}
res.redirect("/menus/");
});
I am trying to $pull the menu with the id of the menu I'm deleting from the current_menus array, but it is not actually updating the menu item. Am I making this too complicated? I'm not sure where I've gone wrong, and other strategies I've found online haven't worked. Any advice is appreciated!