Last active
April 17, 2020 06:02
-
-
Save cicconewk/8fb984cd572a41f8034d77004a2667c1 to your computer and use it in GitHub Desktop.
#mongoose #unique validator #validator #unique mongoose
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
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