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

72
Visualizações
How to create a mongoose object and simultaneously log the _id

I'm creating subdocuments in my event model under guests that look like below. I would like to console.log the corresponding subdoc Id as each guest id is created.

 {
   "guests" : [ 
          { "phone" : 11111, 
            "_id" : ObjectId("61ef629981f154bead6b0de4") 
          }, 
          { "phone" : 4444444444, 
            "_id" : ObjectId("61fca19f95b626e017732139") 
          } 
       ]
  }

I followed the mongoose docs but the code from the docs (below) only logs the first id even as each subsequent doc is created because of the index 0.

// create a comment
parent.children.push({ name: 'Liesl' });
const subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true

I tried removing the index 0 and the console log just produces the ever-growing guests array.

module.exports.addGuest = async (req, res) => {
    const event = await Event.findById(req.params.id);
    const phone = req.body.guest;
    event.guests.push(phone);
    const guestId = event.guests[0];
    console.log(guestId);
    await event.save();
    res.redirect(`/events/${event._id}`);
}

How do I adjust my function to log the corresponding subdoc Id as it's created?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

try applying mongoose hooks on your subschema. mongoose pre save hook is triggered every time a document is saved in your collection and you can log the id of your document which is being saved.

about 4 years ago · Juan Pablo Isaza Relatório
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