mongoose-unique-validator npm code example
Example 1: mongoose unique validator
npm install --save mongoose-unique-validator
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var mySchema = mongoose.Schema();
mySchema.plugin(uniqueValidator);
Example 2: express unique validator for the owner
schmea.post('save', function(error, doc, next) {
if (error.name === 'MongoError' && error.code === 11000) {
next(new Error('email must be unique'));
} else {
next(error);
}
});