猫鼬+ lodash错误地扩展了对象的复制数组 [英] Mongoose + lodash extend copying array of object incorrectly

查看:54
本文介绍了猫鼬+ lodash错误地扩展了对象的复制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个架构

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

这是我的控制器函数,用于在模式中放置/更新OtherExp字段.

This is my controller function called for put / update of OtherExp fields in the schema.

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

My data is say Row 1: a1, a2, a3, a4, a5,, a6, a7 Row 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

Problem is data getting saved to my mongodb collection is a repeat of the first row Row 1: a1, a2, a3, a4, a5,, a6, a7 Row 2: a1, a2, a3, a4, a5,, a6, a7

任何人都可以看到问题所在吗? 相同的代码对于我的架构的其他部分也可以正常工作,在这些地方我没有像这样的嵌套数据.

Can anyone see what might be the issue ? The same code works fine for other parts of my schema where I have no nesting of the data like in this one.

这是从我的候选人资料/index.js

This is from my candidateProfile / index.js

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

推荐答案

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

I've just wasted 1 hour on similar issue. I've used _.assign{In}(), then _.merge() then tried also Document#set() i've always ended with repeated entries in array.

对我有用的解决方法

  • []分配给将要设置的任何数组
  • 然后使用doc.set(attrs)
  • 分配整棵树
  • assign [] to any array that is about to be set
  • then assign whole tree using doc.set(attrs)

示例(在我的情况下,some_problematic_array引起了与所讨论的问题相同的奇怪行为):

Example (in my case, some_problematic_array caused same strange behaviuour as in question):

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);

这篇关于猫鼬+ lodash错误地扩展了对象的复制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆