MongoDB - 当嵌套键是变量时,从对象中删除($ unset)嵌套键

时间:2016-12-18 16:28:04

标签: javascript mongodb unset

请考虑教师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',
  }
  ...
}

我们还将拥有处理所有这些伟大的功能。我尝试了几种不同的mongo.update()组合,似乎没有什么是正确的。这是一个关于我认为会起作用的例子,但仍然没有。

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

目标:

计划(删除)Johnny Appleseed从预定的2016年12月18日开始,所以完成的文档将如下所示:

{
  _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',
  }
  ...
}

请帮助和谢谢!

2 个答案:

答案 0 :(得分:2)

使用变量作为属性名称时,需要使用computed property name语法,方法是将其括在方括号中:

Instructors.update({ fullName: _instrName }, { $unset: { [_scheduleKey]: 1 } });

答案 1 :(得分:0)

'1 2 3 4 5 1 2 6 7 1 2 6 8 9'