Skip to content Skip to sidebar Skip to footer

Mongoose Expand Default Validation

I want to build 'minLength' and 'maxLength' in the mongoose schema validation rules, the current solution is: var blogSchema = new Schema({ title: { required: true, type: String

Solution 1:

Check out the library mongoose-validator. It integrates the node-validator library for use within mongoose schemas in a very similar way to which you have described.

Specifically, the node-validatorlen or min and max methods should provide the logic you require.

Try :

var validate = require('mongoose-validator').validate;

var blogSchema = newSchema({
 title: {
    type: String,
    required: true,
    validate: validate('len', 8, 32)
 }
});

Solution 2:

maxlength and minlength now exist. You code should work as follows.

var mongoose = require('mongoose');
    var blogSchema = new mongoose.Schema({
        title: {
             type: String,
             required: true,
             minLength: 8,
             maxLength: 32
        }
    });

Solution 3:

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']);
  }
  returnthis;
};

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']);
  }
  returnthis;
};

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.

Solution 4:

Min and max have changed

var breakfastSchema = newSchema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  },
  drink: {
    type: String,
    enum: ['Coffee', 'Tea'],
    required: function() {
      returnthis.bacon > 3;
    }
  }
});

https://mongoosejs.com/docs/validation.html

Post a Comment for "Mongoose Expand Default Validation"