Mongoose + Lodash Extend Copying Array Of Object Incorrectly
I have this schema var CandidateProfileSchema = new Schema({ OtherExp: [{ typeExp:String, organization: String, startDate: String, endDate: String, role: Str
Solution 1:
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.
The workaround that works for me
- assign
[]
to any array that is about to be set - then assign whole tree using
doc.set(attrs)
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);
Solution 2:
I think this might be a typo: if you want to update OtherExp in your candidateProfile, it should be something like this
candidateProfile.OtherExp = _.extend(candidateProfile.OtherExp, req.body.OtherExp);`
candidateProfile.save(//... etc)
Solution 3:
Mongoose models with nested enumerables mess up with lodash merge or extend.
Try first aggregating your data before assigning.
vardata = _.merge(candidateProfile.toJSON(), req.body);
candidateProfile.other = _.extend(candidateProfile.other, data.other);
Post a Comment for "Mongoose + Lodash Extend Copying Array Of Object Incorrectly"