Created
July 15, 2015 03:04
-
-
Save secretfader/5566a3245db4efc36f22 to your computer and use it in GitHub Desktop.
Mongoose Unique Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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