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

70
Views
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 answers
Answer question

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 Report
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!