3

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?

1 Answer 1

1

You can perform upsert to get the desired results

Users.update({ name: "Joe Bloggs", "events.date" : 1378335600 },{ $push: {"events.venues": 1}},{ upsert: true }, function(err{...})
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't solve the problem: In the case where an event doesn't exist with the correct date it will replace the events array with the object. Also - the upsert flag cannot be used with the $ positional operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.