I have the following model inmongoose
import mongos from 'mongoose'
import validator from 'mongoose-unique-validator'
const schema = new mongos.Schema({
name: {
type : String,
required : [ true, 'El nombre del rol es necesario' ],
unique : [ true, 'Ya existe un rol con ese nombre' ],
max : [ 50, 'El nombre no puede exceder los 50 caracteres' ],
min : [ 3, 'El rol debe contener 3 o más caracteres' ]
},
status : { type: String, default: 'active' },
addedBy : { type: mongos.Types.ObjectId, ref: 'User' },
addedDate : { type: Date, default: Date.now },
modification : {
user : { type: mongos.Types.ObjectId, ref: 'User' },
date : { type: Date, default: Date.now },
current : { type: String },
updated : { type: String }
}
}, { collection: 'roles' } )
schema.plugin( validator, { message: 'Ya existe {VALUE} en la base de datos' } )
const RoleModel = mongos.model( 'Role', schema )
export default RoleModel
When I start the validations:
- passed the
required
- passed the
unique
- Did not pass the
max
(Makes the insertion) - Did not pass the
min
(Makes the insertion)
I don't understand what I'm doing wrong, can you help me?
The problem is that you are using the wrong validation for the type of field you want to validate.
Mongoose's built -in validations
min
andmax
are validations used for data typesNumber
, and you want to validate data typesString
.The validations you should use for a type
String
areminlength
andmaxlength
.Your Mongoose schema should look like this:
I hope this clears your doubt.