Mongoose: Adding minlength and maxlength to Schema with String as type

Created on 24 Apr 2013  路  13Comments  路  Source: Automattic/mongoose

Add a new feature for minimum length and maximum length to Schema with String as type. This will validate minimum and maximum length to corresponding string in schema.

For example,

var s = new Schema({ name: { type: String, minlength: 5, maxlength: 15 }});

OR

var s = new Schema({ name: { type: String, min: 5, max: 15 }});

Most helpful comment

Here is the documentation for the new minlength validator http://mongoosejs.com/docs/api.html#schema_string_SchemaString-minlength

All 13 comments

This belongs as a plugin.

Can you please be more specific?

I can't find a plugin regarding this feature.

You could extend the string schematype similar to how match works.

The plugin would just require mongoose and add the function to mongoose.Schema.Types.String.prototype.

I think, SchemaString.prototype.minlength and SchemaString.prototype.maxlength can be easily added similar to min and max methods implemented for number schema with slight change. IMO, I don't think it needs to be a plugin as it's similar feature like min and max methods of number schema. So it needs to come as feature provided by mongoose, not by additional plugin.

Not gonna happen. Mongoose is bloated enough and exposes the apis necessary to extend it.

Hi,

This can be handled using path function like this:

var Person = new Schema({
title : { type: String, required: true }
, age : { type: Number, min: 5, max: 20 }
, meta : {
likes : [String]
, birth : { type: Date, default: Date.now }
}
});

Person.path('title').validate(function (v) {
return v.length > 50;
});

@sandesh27, thank you for workaround

Its in 4.0.0-rc2 :)

Here is the documentation for the new minlength validator http://mongoosejs.com/docs/api.html#schema_string_SchemaString-minlength

Just stumbled upon this. I personally think the ORM/ODM should include as few validations and whatnot built-in, as these are really application concerns, and there are plenty of libraries for this. Keep it lean :)

how to present date type in schema

Was this page helpful?
0 / 5 - 0 ratings