如何使用多个动态密钥更新mongodb文档?

时间:2018-05-06 13:33:11

标签: node.js mongodb mongoose

服务器收到三个动态参数:map,section,subsection。

如何在某些小节中使用mongoose更新用户技能?

用户模型:

{
  _id: some_id,
  skills: {
    [map_id]: {
      [section_id]: { 
        [subsection_id]: {
          ...new_data
        }
      }
    },
    ...other mapKeys
  }
}

现在我用:

userScheme.findById(userId, function(userErr, user) {
  const body = req.body,
        map_id = body.map,
        section_id = body.section,
        subsection_id = body.subsection,
        new_data = body.data;

  let skills = {};
  let createNestedObject = function( base, names ) {
      for( var i = 0; i < names.length; i++ ) {
         base = base[ names[i] ] = base[ names[i] ] || {};
      }
  };

  createNestedObject( skills, [map, section, subsection] );
  skills[map_id][section_id][subsection_id] = new_data;

  user.skills = skills;
  user.save();
});

但它会覆盖之前收到的数据:(

1 个答案:

答案 0 :(得分:0)

我使用Model.update(mongoose方法):

const link = `skills.${map_id}.${section_id}.${subsection_id}`;
userModel.update({_id: userId }, { $set: { [link]: subsection } }, { upsert: true }, function(userErr, user) {});

它正常工作!