For the following document in a collection 'users':
{
_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>]
}
]
}
Question: I would like to push a new venue_id to the venues array for a given date.
However if an event object does not exist with the corresponding date a new event object will be push to the events array with the new date and the venue pushed to the venues array.
Current solution:
Try the update with the date, if this fails, then we know the new event object needs to be created. Something like this:
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.
}
});
Is there a cleaner solution to this problem?