title: Node.js Mongoose, how to catch error in post save
body: <p>I have a collection with a unique field on it. Let's say I create the value of this unique field in the pre save method like this:</p>
  
  <pre><code>schema.pre('save', function (next) {
      var _self = this;
      try {
          if (config.devMode) {
              log.debug('[' + si.name + ':write] - Executing presave on: ' + _self._id);
          }
          if(!_self.transaction_id){
              _self.transaction_id = powm(30).toLowerCase();
          }
          next();
      } catch (e) {
          log.error('[' + si.name + ':write] - threw an error (SAVE): ', e.stack, _self);
          next(e);
      }
  });
  </code></pre>
  
  <p>Powm creates an aleatory string like 'dfjkfj3434jkl23k4j2k3j4asdf', which needs to be unique. Although the string is long enough to not be duplicated, I want to be sure that if it is I can retry the saving with a new one till there is a really unique value on it. </p>
  
  <p>I know MongoDB throws an error that bubbles up when saving the document like this: </p>
  
  <pre><code>documentname.save(function(err, doc){
     // If mongodb unique error then reset with a new id and resave
  });
  </code></pre>
  
  <p>But this forces me to look for all places in the code where this happens. So I was wondering if I can catch this error in the post mongoose middleware. The problem is that no error object seems to be passed to post save method. So, any idea on this? Thanks!</p>