I am trying to use mongoose to validate uniqueness on a username field for a User model
User.schema.path('username').validate(function(value, done) {
User.findOne({username: value}, function(err, user) {
if (err) return done(false);
if (user) return done(false);
done(true);
});
}, "exists");
This all works great when I am creating new users. However when updating a users data my validation fails. Basically because I am trying to edit the same user it is fail validation on. I.E. when updating user username = bob the validation method finds bob and fails.
I have unique: true on my model for that field so mongodb will validate it just fine without my mongoose validation.
var UserSchema = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true }
);
However the problem with letting mongo tell me that I cannot insert data is there is no great way to extract a meaningful error message to send back to the client. i.e. 'sorry username already exists, please pick a new one'
Basically only way I can think of to get around this is if mongoose passed my validator the actual object I am trying to validate rather then just the value. Then I could compare _id's, ie
if (current._id == new._id) //this is the same user don't fail validation on unique username
There is a good mpn module for mongoose uniqueness validation : https://github.com/blakehaswell/mongoose-unique-validator.