Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda