Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
How can I provide default validation for all instances of a custom mongoose SchemaType?

I have followed the mongoose documentation for creating Custom Schema Types. My implementation is functional, but does not yield the results I would like.

My goals is to have a custom schemaType that provides a custom error message when casting fails (or when casting succeeds but validation fails), without having to declare a validation method each time the data type is used in my api's schemas.

Here is an example (I will try to explain in the comments):

const mongoose = require('mongoose')

// Create Custom Schema Type
class UUIDv4 extends mongoose.SchemaType {
    constructor(key, options) {
        super(key, options, 'UUIDv4');
    }

    cast(val) {
        if (/*Do UUIDv4 validation check here*/) {

            /* Because of the way mongoose works, this error message is difficult
               to present to a user because the built-in casting error message is 
               always used at the top level.
             */
            throw new Error(`${val} is not a valid version 4 UUID`);
        }
        return val;
    }
}

// Add `UUIDv4` to the type registry
mongoose.Schema.Types.UUIDv4 = UUIDv4;

const entitySchema = new mongoose.Schema({
    entityKey: {
        type: UUIDv4,
        required: true
    }
})

const Entity = mongoose.model('Entity', entitySchema)

const testEntity = new Entity({
    entityKey: "123456789"
})

testEntity.save().then(() => {
    console.log('done')
}).catch((e) => {
    console.log(e.errors.entityKey.reason.message) // This is where the custom message can be found
})

Obviously, I could skip creating the custom SchemaType, but I was hoping to avoid having to specify a custom validator each time an entityKey is used in my schemas (they are used a lot).

const UUIDv4Validator = {
    validator: function(v) {
        // If is valid. . . return true
        // else return false
    },
    message: 'Invalid UUIDv4'
}

const entitySchema = new mongoose.Schema({
    entityKey: {
        type: String,
        required: true,
        validate: UUIDv4Validator // I don't want to have to do this every time
    }
})

I know that I could keep the custom Schema Type and check for the existence of this error in my try/catch statements using the optional chaining operator, but I would rather avoid the need, as it will be repetitive:

try {
    // do stuff . . .
    await testEntity.save()
} catch (e) {
    const message = e?.errors?.entityKey?.reason?.message ?? e.message. // No thank you!
    // do stuff . . .
}

I tried reading the documentation to learn how to create a custom validation method for custom Schema Types, but I was unsuccessful at getting any attempts to work and so far I have found no examples online.

How can I have a custom validator permanently linked to my UUIDv4 custom Schema Type that will evaluate the data that is attempting to be saved and, when appropriate, return my custom error message?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I found the answer by following the link in the mongoose SchemaTypes documentation and digging through the source code of some of the mongoose plugins.

Essentially, to make a custom validator that is universally applied to all instances of a mongoose SchemaType, one should pass in a validator directly to the validate() method of the SchemaType.

Inside a custom SchemaType class definition, it can be done by calling the validator method of the super inside the class constructor. Here is an example:

class UUIDv4 extends mongoose.SchemaType {
    constructor(key, options) {
        super(key, options, 'UUIDv4');
        
        // Call the validate method of super and pass in a validator
        // function and a message to return when validation fails
        this.validate(function(val){
            return isUUIDv4(val) // Example UUIDv4 validation check
        }, '{PATH}: "{VALUE}" is not a valid version 4 UUID')
    }
    
    // Other class methods such as cast(), etc. . .
}

As shown in the documentation (and in my original question) mongoose validators accept an object {} containing a validator and a message. Although they are frequently added to a schema to provide custom validation for a specific field/path, they can be added to a schemaType's overall validation by calling SchemaType.validate() (where SchemaType is replaced by the actual SchemaType name, i.e. String) and passing in a validator function and message as two separate parameters.

For those working with custom SchemaTypes, such as in my use case, it is possible to get the desired error message from the validator by having the cast() method always return true, and only handling validation on save().

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda