最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongoose expand default validation - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Dec 24, 2012 at 19:29 onlineracoononlineracoon 2,9705 gold badges48 silver badges66 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 11

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

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

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.

Min and max have changed

var breakfastSchema = new Schema({
  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() {
      return this.bacon > 3;
    }
  }
});

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

发布评论

评论列表(0)

  1. 暂无评论