title: Display Flash Error Messages to User After Mongoose Model Save
body: <p>I have a page <code>index.js</code> which has a form to add users, and beside it a list of users in the database.</p>
  
  <h2>/routes/index.js</h2>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var User = require('../schemas/user');
  
  router.post('/create', function(req, res, next) {
    var user = new User({
      username: req.body.username,
      email: req.body.email,
      password: req.body.password
    });
    user.save(function(err) {
      if (err) {
        console.log('user save error ' + err.errmsg);
        return res.json(err.errmsg);
      }
      res.redirect('/');
    });
  });
  
  /* GET home page. */
  router.get('/', function(req, res, next) {
    User.find(function (err, users) {
      if (err) {
        console.log('get error ' + err);
        //return res.sendStatus(500);
      }
      res.render(
        'index',
        {
          userList : users
        }
      );
    });
  });
  
  module.exports = router;
  </code></pre>
  
  <h2>/schemas/user.js</h2>
  
  <pre><code>var mongoose = require('mongoose');
  var Schema = mongoose.Schema;
  
  var userSchema = new Schema({
    username: { type: String, required: true, unique: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    group: String,
    created_at: Date,
    updated_at: Date
  });
  
  var User = mongoose.model(
    'User',
    userSchema
  );
  
  module.exports = User;
  </code></pre>
  
  <p>Here is my view:</p>
  
  <h2>/views/index.pug</h2>
  
  <pre><code>extends layout
  
  block content
    h1= title
    p Welcome to #{title}
  
    .container
      .row
        .col-sm
          h1 Create User
          form(
            method='POST'
            action='/create'
          )
            .form-group
              label(for='username') Username:
              input#username.form-control(
                type='text',
                placeholder='Enter username...',
                name='username'
              )
              if usernameError
                p.error= usernameError
            .form-group
              label(for='password') Password:
              input#password.form-control(
                type='password',
                placeholder='Enter password...',
                name='password'
              )
              if passwordError
                p.error= passwordError
            .form-group
              label(for='email') Email:
              input#email.form-control(
                type='email',
                placeholder='Enter email...',
                name='email'
              )
              if emailError
                p.error= emailError
            button.btn.btn-primary(
              type='submit',
            ) Submit
        .col-sm
          h2 User List
          ul
            each user in userList
              li= user.username
  </code></pre>
  
  <p>As you can see, I have some conditionals in my <code>index.pug</code> file. What I want to do is if an error occurs I want to assign a message to a variable based on the error type (i.e. username already taken, or password too short) and pass that variable over to my pug view. The view will then render the message <strong>if</strong> the proper variable is set. Can somebody help me out? I'm mostly struggling with the fact that I also have to render the list of users, if I try to find users within the error catching part of the post node complains about headers already being set, i.e. If I have my router.post function like so:</p>
  
  <pre><code>router.post('/create', function(req, res, next) {
    var user = new User({
      username: req.body.username,
      email: req.body.email,
      password: req.body.password
    });
    user.save(function(err) {
      if (err) {
        console.log('user save error ' + err.errmsg);
        User.find(function (err2, users) {
          if (err2) {
            console.log('get error ' + err2);
            //return res.sendStatus(500);
          }
          res.render(
            'index',
            {
              userList : users,
              usernameError: err.errmsg
            }
          );
        });
      }
      res.redirect('/');
    });
  });
  </code></pre>
  
  <p>Then I expect to see the usernameError message filled in my view but instead I get an error from the node server:</p>
  
  <pre><code>user save error E11000 duplicate key error collection: test.users index: username_1 dup key: { : "John" }
  POST /create 302 71.995 ms - 46
  Error: Can't set headers after they are sent.
  </code></pre>