猫鼬 + lodash 扩展对象复制数组不正确

Mongoose + lodash extend copying array of object incorrectly

本文关键字:复制数组 不正确 对象 扩展 lodash 猫鼬      更新时间:2023-09-26

>我有这个模式

var CandidateProfileSchema = new Schema({
  OtherExp: [{
    typeExp:String,
    organization: String,
    startDate: String,
    endDate: String,
    role: String,
    description: String,
    achievements: String
  }],
  //more fields
});

这是我的控制器函数,用于在架构中放置/更新 OtherExp 字段。

exports.updateOtherExp = 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.other= _.extend(candidateProfile.other, req.body.other);
    candidateProfile.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, candidateProfile);
    });
  });
};

我的数据是说第 1 行:a1、a2、a3、a4、a5、、a6、a7第 2 行:b1、b2、b3、b4、b5、、b6、b7

问题是保存到我的 mongodb 集合中的数据是第一行的重复第 1 行:a1、a2、a3、a4、a5、、a6、a7第 2 行:a1、a2、a3、a4、a5、、a6、a7

任何人都可以看到可能的问题是什么吗?相同的代码适用于我的架构的其他部分,其中我没有像这个那样嵌套数据。

这是来自我的候选人个人资料/索引.js

router.put('/:id', controller.update);
router.put('/:id/skills', controller.updateSkills);
router.put('/:id/otherExp', controller.updateOtherExp);

我只是在类似的问题上浪费了 1 个小时。我用过_.assign{In}(),然后_.merge()然后也尝试了Document#set()我总是以数组中的重复条目结尾。

对我有用的解决方法

  • []分配给即将设置的任何数组
  • 然后使用doc.set(attrs)分配整个树

示例(就我而言,some_problematic_array引起了与所讨论的相同的奇怪行为):

var attrs = _.pick(req.body, [
    'name',
    'tags', // ...
    "some_problematic_array"
]);
var doc = ///... ;
if( attrs.some_problematic_array ) doc.some_problematic_array = [];
                                      ^^^^ ***workaround***
doc.set(attrs);

我认为这可能是一个错字:如果你想在你的候选人个人资料中更新 OtherExp,它应该是这样的

candidateProfile.OtherExp = _.extend(candidateProfile.OtherExp, req.body.OtherExp);`
candidateProfile.save(//... etc)
具有

嵌套枚举的猫鼬模型会弄乱lodash合并或扩展。

在分配之前,请尝试先聚合数据。

var data = _.merge(candidateProfile.toJSON(), req.body);
candidateProfile.other = _.extend(candidateProfile.other, data.other);