0

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.

5
  • Isn't that the normal behaviour for_.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 $set with .update() instead. Even from the docs "..Array and plain object properties are merged recursively.." Commented Mar 19, 2016 at 1:48
  • Actually on re-read you want to append to the array. You should use $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. Commented Mar 19, 2016 at 1:53
  • I actually wanted to stick to a clean CRUD api. I'm not sure how I would do that with your approach, since it requires creating special-purpose routes, no? Commented Mar 19, 2016 at 1:59
  • Possible duplicate of How to push to a MongoDB array with AngularJS? Commented Mar 19, 2016 at 2:48
  • So I thought I'd seen something like this before. "Must create new routes?" Well you don't have to but it would certainly be more logical to POST new items to an array rather than PUT the whole object. The[ linked example](stackoverflow.com/questions/31667759/…) has both responses. And I disagree completely that the .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. Commented Mar 19, 2016 at 2:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.