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?
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.