Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose schema set max length for a String [duplicate]

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.

like image 775
Fab Avatar asked Mar 03 '15 10:03

Fab


People also ask

What is trim true in Mongoose schema?

If you add { type: String, trim: true } to a field in your schema, then trying to save strings like " hello" , or "hello " , or " hello " , would end up being saved as "hello" in Mongo - i.e. white spaces will be removed from both sides of the string.

Can I set default value in Mongoose schema?

You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.

What does save () do in Mongoose?

save() is a method on a Mongoose document. The save() method is asynchronous, so it returns a promise that you can await on. When you create an instance of a Mongoose model using new, calling save() makes Mongoose insert a new document.

What does Mongoose unique validator do?

mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.


1 Answers

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}
});
like image 142
victorkt Avatar answered Oct 11 '22 14:10

victorkt