Skip to content

Instantly share code, notes, and snippets.

@cicconewk
Last active April 17, 2020 06:02
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 cicconewk/8fb984cd572a41f8034d77004a2667c1 to your computer and use it in GitHub Desktop.
Save cicconewk/8fb984cd572a41f8034d77004a2667c1 to your computer and use it in GitHub Desktop.
#mongoose #unique validator #validator #unique mongoose
Schema.post('save', function (error, doc, next) {
if (error.name === "MongoError" && error.code === 11000) {
const result = {
message: "ValidationError",
errors: {},
};
Object.keys(this._doc).forEach(path => {
const isDuplicate = error.errmsg.includes(`$${path}_1`);
if (isDuplicate) {
const value = this._doc[path];
result.errors[path] = {
message: 'is already used',
kind: 'unique',
path,
value,
}
}
});
next(result);
} else {
next()
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment