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 }
});

blogSchema.path('title').validate(function(value) {
  if (value.length < 8 || value.length > 32) return next(new Error('length'));
});

However I think this should be simplified by just adding custom schema rules like so:

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

How can I do this, is this even possible?

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-validator len or min and max methods should provide the logic you require.

Try :

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

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

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.