2

Consider this document of lesson start times for the instructor Johnny Appleseed:

{
  _id: 'ka83nala9cya9epsj',
  fullName: Johnny Appleseed,
  schedule: {
   '11/05/2016': '12:30',
   '11/15/2016': '2:30',
   '11/16/2016': '1:30',
   '12/07/2016': '9:30',
   '12/18/2016': '10:30', 
   '12/23/2016': '8:30',
  }
  ...
}

We'll also have a function to handle all of this greatness. I've tried a few different mongo.update() combinations and nothing seems to be quite right. Here's an example on what I thought would of work but still doesn't.

function removeStartTime(_instrName, _lessonDate) {
  const _scheduleKey = `schedule.${_lessonDate}`;
  return Instructors.update({ fullName: _instrName }, { $unset: { _scheduleKey: 1 } });
}

The Goal:

Unschedule (remove) Johnny Appleseed from the scheduled 12/18/2016 date so the finished document will look like this:

{
  _id: 'ka83nala9cya9epsj',
  fullName: Johnny Appleseed,
  schedule: {
   '11/05/2016': '12:30',
   '11/15/2016': '2:30',
   '11/16/2016': '1:30',
   '12/07/2016': '9:30',
   '12/23/2016': '8:30',
  }
  ...
}

Please help and thanks!

2 Answers 2

2

You need to use the computed property name syntax when using a variable as a property name by surrounding it in square brackets:

Instructors.update({ fullName: _instrName }, { $unset: { [_scheduleKey]: 1 } });
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! Thank you. I've used computed property name syntax several times before but always in this obj[key] = 'someValue'; context, never wrapped then entire variable in square brackets before, which now makes plenty of since in a hand-slap-to-the-forehead sort of way. :) Thanks again.
0

Instructors.update({fullName: _instrName},{"$unset": {"schedule.12/18/2016": ""} })

1 Comment

This may answer the question, but is not as helpful as it could be. Please explain what was wrong with OPs code, why your changes worked, and possibly how your solution differs from the other solutions here.

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.