Ad

Custom Validations In Mongoose 5.7.0

Previously I was using an older version of mongoose i.e 4.3.7 and the custom schema validations as a pre-save hook worked fine. All I had to was to send the errors to the callback function.

Now after upgrading to the latest version of mongoose, the same validation functions do not work anymore.

My schema looks like this:

var UserSchema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
    validate: [validateUniqueEmail, 'E-mail address is already in-use'],
    lowercase: true
  }
}

In mongoose 4.3.7 the validation function looked like this:

var validateUniqueEmail = function(value, callback) {
  var User = mongoose.model('User');
    User.find({
        $and: [{
            email: value
        }, {
            _id: {
                $ne: this._id
            }
        }]
    }, function(err, user) {
        callback(err || user.length === 0);
    });
};

In the above code, the "callback" variable would be the post save callback which automatically comes in during .save() call and everything works fine.

But when I upgrade to the latest version of mongoose, the value of "callback" variable inside the validateUniqueEmail is null.

I have not found any relevant examples on the web on how to do this for the latest version of mongoose. I have tried to send true/false but that does not work too.

Any help would be great!

Ad

Answer

Implicit async custom validators (custom validators that take 2 arguments) are deprecated in mongoose >= 4.9.0. And in the docs, it also says:

If you prefer callbacks, set the isAsync option, and mongoose will pass a callback as the 2nd argument to your validator function.

So in newer versions, you need to specify isAsync option to make it work. Something like this:

var UserSchema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true,
    validate: {
      isAsync: true,
      validator: validateUniqueEmail, 
      message: 'E-mail address is already in-use'
    },
    lowercase: true
  }
}

Read more in mongoose release notes.

Ad
source: stackoverflow.com
Ad