Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

71
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda