title: Saving an object (with defaults) in Mongoose/node
body: <p>I have an object passed to a function, and want to save a DB entry with those values, with the option to have some defaults.</p>
  
  <p>In practical terms...</p>
  
  <p>I have a schema like this in Mongoose:</p>
  
  <pre><code>var Log = new Schema({
    workspaceId    : { type: String, index: true },
    workspaceName  : { type: String, index: true },
    loginSession   : { type: String, index: true },
    loginToken     : { type: String, index: true },
    logLevel       : { type: Number, enum:[0,1] },
    errorName      : { type: String, index: true },
    message        : { type: String, index: true },
    reqInfo        : { type: String },
    data           : { type: String },
    loggedOn       : { type: Date, index: true },
  });
  mongoose.model('Log', Log);
  </code></pre>
  
  <p>To write things on this table, I have something like:</p>
  
  <pre><code>exports.Logger = function(logEntry){
    var Log = mongoose.model("Log"),
        req = logEntry.req;
  
    log = new Log();
  
    // Sorts out log.reqInfo
    if ( logEntry.req){
      log.reqInfo = JSON.stringify({
        info   : req.info,
        headers: req.headers,
        method : req.method,
        body   :req.body,
        route  :req.route,
        params: req.params    
      });
    } else {
      logEntry.reqInfo = {};
    }
  
    // Sorts out all of the other fields with sane defaults.
    // FIXME: improve this code, it's grown into something ugly and repetitive
    log.workspaceId = logEntry.workspaceId ? logEntryworkspaceId. : '';
    log.workspaceName = logEntry.workspaceName ? logEntry.workspaceName : '';
    log.loginSession = logEntry.loginSession ? logEntry.loginSession : '';
    log.loginToken = logEntry.loginToken ? logEntry.loginToken : '';
    log.logLevel = logEntry.logLevel ? logEntry.logLevel : 0;
    log.errorName = logEntry.errorName ? logEntry.errorName : '';
    log.message = logEntry.message ? logEntry.message : '';
    log.data = logEntry.data ? logEntry.data : {};
  
    // Sorts out log.loggedOn
    log.loggedOn = new Date();
    log.save();
  } 
  </code></pre>
  
  <p>This is absolutely awful code. What's a better way of writing it, without the repetition?</p>