mongoose custom validation using 2 fields

后端 未结 6 1503
余生分开走
余生分开走 2020-11-27 05:00

I want to use mongoose custom validation to validate if endDate is greater than startDate. How can I access startDate value? When using this.startDate, it d

6条回答
  •  北海茫月
    2020-11-27 05:45

    Using 'this' within the validator works for me - in this case when checking the uniqueness of email address I need to access the id of the current object so that I can exclude it from the count:

    var userSchema = new mongoose.Schema({
      id: String,
      name: { type: String, required: true},
      email: {
        type: String,
        index: {
          unique: true, dropDups: true
        },
        validate: [
          { validator: validator.isEmail, msg: 'invalid email address'},
          { validator: isEmailUnique, msg: 'Email already exists'}
        ]},
      facebookId: String,
      googleId: String,
      admin: Boolean
    });
    
    function isEmailUnique(value, done) {
      if (value) {
        mongoose.models['users'].count({ _id: {'$ne': this._id }, email: value }, function (err, count) {
          if (err) {
            return done(err);
          }
          // If `count` is greater than zero, "invalidate"
          done(!count);
        });
      }
    }
    

提交回复
热议问题