title: Express cookieSession and Mongoose: how can I make request.session.user be a Mongoose model?
body: <p>When a new user account is created, I create newUser, a Mongoose model instance that looks like:</p>
  
  <pre><code>_events: Object
  errors: undefined
  isNew: false
  save: function () {
  arguments: null
  caller: null
  _doc: Object
    name: 'Joe Smith'
  ...
  </code></pre>
  
  <p>The actual data for the object is in the <strong>_doc</strong> property, though getters and setters exist so you can run: </p>
  
  <pre><code>user.name = 'Jane Doe' 
  </code></pre>
  
  <p>and that will work fine. I run:</p>
  
  <pre><code>request.session.user = newUser;
  </code></pre>
  
  <p>To save the user to the session. So far, so good.</p>
  
  <p>However, in subsequent requests, request.session.user seems to be only the stuff in _doc. Eg:</p>
  
  <pre><code>name: 'Joe Smith'
  </code></pre>
  
  <p>Which is nice, but that means I can't run eg, <strong>request.session.user.save()</strong> to save changes.</p>
  
  <p>I could simply make some middleware to look up the user associated with the data. But I'd like to know more about what Express and Mongoose are doing here.</p>
  
  <p>How can I make request.session.user be a Mongoose model?</p>
  
  <p><strong>Update</strong>: my current middleware hack:</p>
  
  <pre><code>// Use as a middleware on routes which need users
  // TODO: only needed due to request.session.user being saved weirdly
  var rehydrateUser = function(request, response, next) {
    if ( request.session.user ) {
      var hydrated = request.session.user.save
      if ( ! hydrated ) {
        console.log('Rehydrating user...');
        models.User.findOne({ somefield: request.session.user.somefield }, function (err, user) {
          if ( err ) {
            request.session.error = 'User not found in DB!';
            request.redirect('/');
          } else {
            request.session.user = user;          
            console.log('Rehydrated user! All repos already being monitored.');
            next();
          }
        })
      } else {
        next();
      }
    } else {
      console.log('No user in session')
      next();
    }
  }
  </code></pre>