2

I am running into a question when to use which one, the following is update function for mongoose, it works fine.

// Updates an existing form in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Form.findById(req.params.id, function (err, form) {
    if (err) { return handleError(res, err); }
    if(!form) { return res.send(404); }
    var updated = _.assign(form, req.body);
    updated.formContent = req.body.formContent;
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, form);
    });
  });
};

Tried the following to replace the form data.

_.assign(form, req.body); // Works (update database)
_.merge(form, req.body);  // Not Work (database not updating, remain the same)
_.extend(form, req.body); // Works (update database)

The above result show merge doesn't work when there is object within the post data.

Could some please explain why one is not working the others is ok. I have read the following question

Lodash - difference between .extend() / .assign() and .merge()

but i am curious to understanding which one won't update the database, but when applied with assign and extend it's working.

Community
  • 1
  • 1
Bill
  • 17,872
  • 19
  • 83
  • 131

1 Answers1

1

In the given code snippet, the difference in behavior between _.assign(), _.merge(), and _.extend() when updating the database can be attributed to the way these methods handle objects within the post data.

_.assign() and _.extend() perform a shallow copy, meaning they copy the properties of the source object (req.body) to the target object (form) directly. This includes nested objects, allowing the database to be updated correctly.

On the other hand, _.merge() performs a deep merge, recursively merging the properties of the source and target objects. However, _.merge() does not modify the target object directly, but instead returns a new merged object. Therefore, in the given context, using _.merge() does not update the form object, resulting in no changes being made to the database.

For a more detailed understanding of the differences between _.extend(), _.assign(), and _.merge(), you can check my project where I used this