I try to update an existing entry in mongoDB. Updating the title works, but if I add a component and run update, the entry remains unchanged.
The schema:
var ProductSchema = new Schema({
title: { type: String },
components: [{ type: mongoose.Schema.ObjectId, ref: 'Component' }]
});
The route:
exports.update = function(req, res) {
Product.findById(req.params.id, function (err, product) {
if (err) { return handleError(res, err); }
if(!product) { return res.send(404); }
var updated = _.merge(product, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.status(200).json(product);
});
});
};
I checked if updated gets merged correctly by lodash, and it does. The .save method also doesn't return an error.
Can it be, that .save() doesn't overwrite (or ignoring) already existing arrays? I checked the documentation, but I can't find anything that explains this behavior.
_.merge()? I thought it was. It's really not a fantastic pattern anyway. If you acutally intend to overwrite content you should rather be using$setwith.update()instead. Even from the docs "..Array and plain object properties are merged recursively.."$push( again an.update()statement ). Using the.findById()and then.save()is multiple trips to the database and all kinds of horible issues including potential overwrites of other concurrent requests..find()and.save()pattern is "clean" at all. It's really quite dirty and horrible, and full of concurrency problems as mentioned, both here an in the other response.