Mongoose expand default validation

后端 未结 4 541
天涯浪人
天涯浪人 2021-01-06 17:49

I want to build \"minLength\" and \"maxLength\" in the mongoose schema validation rules, the current solution is:

var blogSchema = new Schema({
  title: { re         


        
4条回答
  •  渐次进展
    2021-01-06 18:07

    I had the same feature request. Don't know, why mongoose is not offering min/max for the String type. You could extend the string schema type of mongoose (i have just copied the min / max function from the number schema type and adapted it to strings - worked fine for my projects). Make sure you call the patch before creating the schema / models:

    var mongoose = require('mongoose');
    var SchemaString = mongoose.SchemaTypes.String;
    
    SchemaString.prototype.min = function (value) {
      if (this.minValidator) {
        this.validators = this.validators.filter(function(v){
          return v[1] != 'min';
        });
      }
      if (value != null) {
        this.validators.push([this.minValidator = function(v) {
          if ('undefined' !== typeof v)
            return v.length >= value;
        }, 'min']);
      }
      return this;
    };
    
    SchemaString.prototype.max = function (value) {
      if (this.maxValidator) {
        this.validators = this.validators.filter(function(v){
          return v[1] != 'max';
        });
      }
      if (value != null) {
        this.validators.push([this.maxValidator = function(v) {
          if ('undefined' !== typeof v)
            return v.length <= value;
        }, 'max']);
      }
      return this;
    };
    

    PS: As this patch uses some internal variables of mongoose, you should write unit tests for your models, to notice when the patches are broken.

提交回复
热议问题