更新保存部分数据

Update saving partial data

var CandidateProfileSchema = new Schema({
  Skills: {
    programmingLang: [{text: String}],
    scriptingLang:  [{text: String}],
    tools:  [{text: String}],
    ide:  [{text: String}],
  },
  //more fields
});

exports.updateOptPrefs = function(req, res) {
  console.log( req.body );
  if(req.body._id) { delete req.body._id; }
  CandidateProfile.findOne({userId:req.params.id}, function (err, candidateProfile) {
    if (err) { return handleError(res, err); }
    if(!candidateProfile) { return res.send(404); }

    candidateProfile.Skills.programmingLang= req.body.Skills.programmingLang;
    candidateProfile.Skills.scriptingLang= req.body.Skills.scriptingLang;
    candidateProfile.Skills.tools=req.body.Skills.tools;
    candidateProfile.Skills.ide=req.body.Skills.ide;
    //.... other fields
    candidateProfile.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, candidateProfile);
    });
  });
};

不知何故,这只是复制了 mongodb 文档中的 programmingLang 字段。我们在这个问题上花了大约 5 个小时,如果有人能指出我们在这里犯的错误,我们将非常高兴。

尝试使用 Lo-Dash 扩展:

var _ = require('lodash');
exports.updateOptPrefs = function(req, res) {
    if(req.body._id) { delete req.body._id; }
    CandidateProfile.findOne({userId:req.params.id}, function (err, candidateProfile) {
        if (err) { return handleError(res, err); }
        if(!candidateProfile) { return res.send(404); }
        candidateProfile = _.extend(candidateProfile, req.body);
        candidateProfile.save(function (err) {
            if (err) { return handleError(res, err); }
            return res.json(200, candidateProfile);
        });
    });
 };

你为什么不使用 mongoose update 和 $set ?

CandidateProfile.update( {'userId' : req.params.id}, 
                         {$set : {Skills.programmingLang:req.body.Skills.programmingLang, ...}}, function(err){