I want to build \"minLength\" and \"maxLength\" in the mongoose schema validation rules, the current solution is:
var blogSchema = new Schema({
title: { re
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)
}
});
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
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.
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
}
});