Skip to content

Instantly share code, notes, and snippets.

@secretfader
Created July 15, 2015 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save secretfader/5566a3245db4efc36f22 to your computer and use it in GitHub Desktop.
Save secretfader/5566a3245db4efc36f22 to your computer and use it in GitHub Desktop.
Mongoose Unique Validation
/**
* Dependencies
*/
var MongooseError = require('mongoose/lib/error')
, Promise = require('bluebird');
/**
* Module body / Expose
*/
var parseError = function (err, options) {
options = options || {};
if (err && err.name === 'MongoError' &&
(err.code === 11000 || err.code === 11001)
) {
var field = err.message.split('index: ')[1].split(' ')[0].split('_')[0]
, value = err.message.split('"')[1]
, error = new MongooseError.ValidationError(err);
error.errors[field] = new MongooseError.ValidatorError({
type: 'Duplicate Value',
path: field,
value: value,
message: options.message || null
});
return error;
} else {
return err;
}
};
module.exports = function (schema, options) {
options = options || {};
options.errors = options.errors || {};
schema.methods.write = function () {
var self = this;
return new Promise(function (resolve, reject) {
self.save(function (err) {
err = parseError(err, options.errors.unique);
if (err) return reject(err);
resolve(self);
});
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment