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.
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.
You can also set the default schema option to a function. Mongoose will execute that function and use the return value as the default.
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.
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.
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}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With