UnderscoreJS wont extend object

狂风中的少年 提交于 2019-12-13 04:53:12

问题


I am trying to merge 2 objects using underscore. The destination object is a mongoose model but I have applied lean() to it to make it return a javascript object rather than a mongo document.

model.find({}).lean().exec(function (error, object) {});

I then try extending using underscore

_.extend(object, source);

But it only returns the source object. I have tried with simple objects to test and those worked fine, so I am assuming it has something to do with mongoose?

The simple objects that worked were:

{foo:'foo'},{bar:'bar'}

And the objects that I am trying to merge but haven't been able to are:

{
  _id: 526540eaa77883d815000029,
  name: 'House',
  description: '',
  type: 'residential',
  cost: 100,
  buildTime: 5,
  resources: { produces: [], required: { wood: 5 } },
  population: { provides: 10, required: 0 },
  requires: [],
  maxLevel: 5,
  upgrades:
   { '2': { resourceMultiplier: 1.2, cost: 150, time: 5 },
     '3': { resourceMultiplier: 1.5, cost: 200, time: 7 },
     '4': { resourceMultiplier: 2, cost: 300, time: 10 },
     '5': { resourceMultiplier: 2.5, cost: 500, time: 15 } },
  scale: { x: 1, y: 1, z: 1 } 
}


{ 
  empireId: '52654578a4eff60000000001',
  buildingId: '526540eaa77883d815000029',
  level: 1,
  isComplete: false,
  isUpgrading: false,
  gridId: '175|0|125',
  started: 1382442513823,
  _id: 526666113fccae68be000003,
  __v: 0 
}

Anyone come across this before or know where I am going wrong?


回答1:


Well I am stupid. The source object was gotten from another mongoose query at the top of the file, this one was an instance of mongoose.Document and therefore couldn't be changed. I added lean() to it to make it return a javascript object and it's all working now.



来源:https://stackoverflow.com/questions/19517712/underscorejs-wont-extend-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!