【发布时间】:2022-02-10 16:46:18
【问题描述】:
我正在guests 下的事件模型中创建子文档,如下所示。我想console.log 创建每个访客 ID 时对应的子文档 ID。
{
"guests" : [
{ "phone" : 11111,
"_id" : ObjectId("61ef629981f154bead6b0de4")
},
{ "phone" : 4444444444,
"_id" : ObjectId("61fca19f95b626e017732139")
}
]
}
我遵循mongoose docs,但文档(如下)中的代码仅记录第一个 id,即使由于索引 0 而创建了每个后续文档。
// create a comment
parent.children.push({ name: 'Liesl' });
const subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true
我尝试删除索引 0,控制台日志只生成不断增长的 guest 数组。
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}`);
}
如何调整我的函数以在创建时记录相应的子文档 ID?
【问题讨论】:
标签: javascript node.js mongoose subdocument