title: How to catch the error when inserting a MongoDB document which violates an unique index?
body: <p>I'm building a MEAN app.</p>
  
  <p>This is my Username schema, the username should be unique.</p>
  
  <pre><code>var mongoose = require('mongoose');
  var Schema = mongoose.Schema;
  
  module.exports = mongoose.model('User', new Schema({ 
      username: { type: String, unique: true }
  }));
  </code></pre>
  
  <p>On my post route I save the user like this:</p>
  
  <pre><code>app.post('/authenticate', function(req, res) {
          var user = new User({
              username: req.body.username
          });
  
          user.save(function(err) {
              if (err) throw err;
  
              res.json({
                  success: true
              });
  
          });
      })
  </code></pre>
  
  <p>If I post with the same username again I get this error:</p>
  
  <blockquote>
    <p>MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key
    error index:</p>
  </blockquote>
  
  <p>Can someone explain how instead of the error to send a json like <code>{ succes: false, message: 'User already exist!' }</code></p>
  
  <p>Note: After I post the user I will automatically authentificate, dont need password or something else.</p>