Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Removing an object reference from an array of object references with mongoose

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!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!