在Mongoose中,有没有更好的方法来添加子文档?据我目前所知,我需要先尝试更新文档。当找不到时-我执行推送到子文档的数组。该代码看起来不是很漂亮。您可以分享有关此问题的最佳做法吗?
async (eventId, userId, bet) => {
bet.user = userId;
try {
let event = await Event.findOneAndUpdate({
'_id': eventId,
// 'bettingFinishDate': { $gt: new Date() },
'isDeleted': false,
'bets.user': userId,
'bets.isDeleted': false }, {
'$set': {
'bets.$': bet
}
}, { 'new': true });
if (!event) {
event = await Event.findOne({
'_id': eventId,
'isDeleted': false,
});
event.bets.push(bet);
event = await event.save();
};
return event;
} catch (e) {
throw new Error('An error occurred while adding bet to specified event.');
};
};