How to catch the error when inserting a MongoDB document which violates an unique index?
I'm building a MEAN app. This is my Username schema, the username should be unique. var mongoose = require('mongoose'); var Schema = mongoose.Schema; module.exports = mongoose.model('User', new Schema({ username: { type: String, unique: true } })); On my post route I save the user like this: 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 }); }); }) If I post with the same username again I get this error: MongoError: insertDocument :: caused by :: 11000 E11000 duplicate