UnderscoreJS wont extend object

2019-09-02 13:30发布

问题:

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.