title: Can't Catch Error for Mongoose Model Save
body: <p>I have a simple user schema:</p>
  
  <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>And an index page with a form that is capable of creating a user. I want to display a flash message to the user if the save does not work properly. I know the premise to do this is to create a place for the message in the <code>get</code> route and if the message exists, then render a dom element containing the message. Unfortunately all that I can manage is to crash the server and receive:</p>
  
  <h2>Error message</h2>
  
  <pre><code>events.js:160
        throw er; // Unhandled 'error' event
        ^
  BulkWriteError: E11000 duplicate key error collection: test.users index: email_1 dup key: { : "test@gmail.com" }
      at /home/bob/sites/mysite.ca/projects/login/node_modules/mongodb/lib/bulk/unordered.js:528:15
      at handleCallback (/home/bob/sites/mysite.ca/projects/login/node_modules/mongodb/lib/utils.js:128:55)
      at resultHandler (/home/bob/sites/mysite.ca/projects/login/node_modules/mongodb/lib/bulk/unordered.js:454:5)
      at /home/bob/sites/mysite.ca/projects/login/node_modules/mongodb-core/lib/connection/pool.js:541:18
      at _combinedTickCallback (internal/process/next_tick.js:73:7)
      at process._tickCallback (internal/process/next_tick.js:104:9)
  </code></pre>
  
  <h2>/routes/index.js</h2>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var mongoose = require('mongoose');
  mongoose.connect('mongodb://localhost/test');
  
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'connection error:'));
  db.once('open', function() {
    console.log('index.js db connected!');
  });
  
  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(error) {
      if (error) console.log(error);
      console.log('User ' + user.username + ' successfully created!');
    });
  });
  
  /* GET home page. */
  router.get('/', function(req, res, next) {
    res.render(
      'index',
      {
          title: 'Express'
      }
    );
  });
  
  module.exports = router;
  </code></pre>
  
  <p>How can I catch this error and handle it rather than crashing the node server?</p>