问题
I have this schema
var CandidateProfileSchema = new Schema({
OtherExp: [{
typeExp:String,
organization: String,
startDate: String,
endDate: String,
role: String,
description: String,
achievements: String
}],
//more fields
});
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);
});
});
};
My data is say Row 1: a1, a2, a3, a4, a5,, a6, a7 Row 2: b1, b2, b3, b4, b5,, b6, b7
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.
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:
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);
回答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)
回答3:
Mongoose models with nested enumerables mess up with lodash merge or extend.
Try first aggregating your data before assigning.
var data = _.merge(candidateProfile.toJSON(), req.body);
candidateProfile.other = _.extend(candidateProfile.other, data.other);
来源:https://stackoverflow.com/questions/27771633/mongoose-lodash-extend-copying-array-of-object-incorrectly