title: Lodash merge with mongoose
body: <p>Here is a code snippet of an update method using express.js and mongoose.
  I'm trying to merge the existing mongo entity with the json object from the request payload body.</p>
  
  <pre class="lang-js prettyprint-override"><code>exports.update = function(req, res) {
      if(req.body._id) { delete req.body._id; }
      Entity.findById(req.params.id, function (err, entity) {
          if (err) { return handleError(res, err); }
          if(!entity) { return res.send(404); }
          var updated = _.merge(entity, req.body);
          updated.save(function (err) {
              if (err) { return handleError(res, err); }
              return res.json(200, entity);
          });
      });
  };
  </code></pre>
  
  <p>This unfortunately doesn't work. I'm getting this error</p>
  
  <pre><code>node_modules/mongoose/lib/document.js:1272
      doc.save(handleSave);
          ^
  TypeError: Object #&lt;Object&gt; has no method 'save'
  </code></pre>
  
  <p>I have try to create my own custom <code>merge</code> method but still i cannot achieve a proper merge :</p>
  
  <pre class="lang-js prettyprint-override"><code>exports.update = function(req, res) {
      if(req.body._id) { delete req.body._id; }
      Entity.findById(req.params.id, function (err, entity) {
          if (err) { return handleError(res, err); }
          if(!entity) { return res.send(404); }
          var updated = merger(resume, req.body)//_.merge(resume, req.body);
          updated.save(function (err) {
              if (err) { return handleError(res, err); }
              return res.json(200, entity);
          });
      });
  };
  function merger (a, b) {
      if (_.isObject(a)) {
          return _.merge({}, a, b, merger);
      } else {
          return a;
      }
  };
  </code></pre>
  
  <p>With this variance i'm having this message :</p>
  
  <pre><code>node_modules/mongoose/lib/document.js:1245
        return self.getValue(i);
                ^
  TypeError: Object #&lt;Object&gt; has no method 'getValue'
  </code></pre>
  
  <p>As a result, I am not able to extend the values of <code>entity</code>, and <code>req.body</code> to the destination <code>updated</code>. Only the structure gets copied i guess. Some one please let me know where I am wrong. Thanks.</p>