I'm doing a schema with mongoose in Nodejs. And I'm trying to find a way to limit the number of character in a SchemaString. I found that it is possible to use a regex with the keyword match like :
var schema = new Schema({
{
name: {type: String, match: '/^.{0,20}$/'}
});
But I just want to know if there is some parameter to directly specify a maximum length, like this :
var schema = new Schema({
{
name: {type: String, max: 20}
});
Thank you for your help.
Since Mongoose 4.0.0-rc2, the maxLength validation is available:
var Schema = new mongoose.Schema({
name: {type: String, required: true, maxLength: 20}
});
For versions older than 4.0.0-rc2, there is no such validation built in.
You can however create this validation using path function:
Schema.path('name').validate(function (v) {
return v.length <= 20;
}, 'The maximum length is 20.');
Or you can use mongoose-validator. From the example in their README:
var mongoose = require('mongoose');
var validate = require('mongoose-validator');
var nameValidator = [
validate({
validator: 'isLength',
arguments: [3, 50],
message: 'Name should be between 3 and 50 characters'
}),
validate({
validator: 'isAlphanumeric',
passIfEmpty: true,
message: 'Name should contain alpha-numeric characters only'
})
];
var Schema = new mongoose.Schema({
name: {type: String, required: true, validate: nameValidator}
});
所有评论(0)