MongoDB - Removing ($unset) nested key from object when nested key is a variable

1.6k views Asked by At

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

There are 2 answers

1
JohnnyHK On BEST ANSWER

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 } });
1
Barney On

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