对于集合“用户”中的以下文档:
{
_id: ObjectId(1234),
name: "Joe Bloggs"
events: [
{
date: 1378335600, //timestamp representing the start of day
venues: [<venue_id>, <venue_id>, ...]
},
{
date: 1378249200 //the previous day
venues: [<venue_id>]
}
]
}
问题:我想将一个新的venue_id 推送到给定日期的venues 数组。
但是,如果相应日期的事件对象不存在,则新的事件对象将被推送到带有新日期的 events 数组,并且场所会被推送到场所数组。
当前解决方案:
尝试更新日期,如果失败,那么我们知道需要创建新的事件对象。像这样的东西:
Users.findOneAndUpdate({_id: 1234, "events.date": <timestap>},
{ $push: {"events.$.venues" : <venue_id>} },
function(err, result) {
if(err || !result) {
//Issue another mongoose update to push the new event with
//the new date and add the venue array with the <venue_id>
} else {
//the update was successful as there already was a event object
//with the corresponding date.
}
});
这个问题有更清洁的解决方案吗?