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

192
Vistas
Custom validation error with mongoose

I want to know if is possible to customize the validation errors in mongoose when I try to update a document.

I get this validation error:

{
  "err": {
    "errors": {
      "batch_number": {
        "message": "Path `batch_number` is required.",
        "name": "ValidatorError",
        "properties": {
          "type": "required",
          "message": "Path `{PATH}` is required.",
          "path": "batch_number",
          "value": ""
        },
        "kind": "required",
        "path": "batch_number",
        "value": ""
      }
    },
    "message": "Validation failed",
    "name": "ValidationError"
  }
}

I want to response an error like this

{
    "errors": {
      "batch_number": "Cannot be null or empty"
      }
}

My model definition:

const mongoose = require('mongoose');
const Schema =  mongoose.Schema;

const batchSchema = Schema({
  batch_number:{type: String, required: true},
  work_order_id:{ type: Schema.Types.ObjectId, ref: 'work_orders' ,required: true},
  start_date_time:{type: Date, required: true},
  end_date_time:{type: Date},
  status:{type: String},
},
{
  timestamps: true
});

const Batch = module.exports = mongoose.model('batches',batchSchema);

If I get more errors in other field the response must be:

{
    "errors": {
      "batch_number": "Cannot be null or empty",
      "start_date_time": "must be a date"
      }
}

Thanks in advance

UPDATE:

I follow the suggestion from Andre and I get the same error message

const express = require('express')
Batch = require('./../../database/controllers/production/batches');

function mongooseErrorHandler (err, req, res, next) {
    if (err.errors) {
      console.log(err);
        const error = {};
        const keys = Object.keys(err.errors);

        keys.forEach((key) => {
            let message = err.errors[key].message;

            if (err.errors[key].properties && err.errors[key].properties.message) {
                message = err.errors[key].properties.message.replace('`{PATH}`', key);
            }

            message = message.replace('Path ', '').replace(key,'').trim();
            error[key] = message;
        });
        return res.status(500).json(error);
        //return next(error);
    }

    next();
};

module.exports = function(app){
  app.put('/api/batches/:_id',mongooseErrorHandler,(req, res, err) => {
      var id = req.params._id;
      var batch = req.body;
      Batch.update(id, batch,{}, (err, batch) => {
          res.status(200).json(batch);
      });
  });
}
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You should create a middleware to handle mongoose errors:

function mongooseErrorHandler (err, req, res, next) {
    if (err.errors) {
        const error = {};
        const keys = Object.keys(err.errors);

        keys.forEach((key) => {
            let message = err.errors[key].message;

            if (err.errors[key].properties && err.errors[key].properties.message) {
                message = err.errors[key].properties.message.replace('`{PATH}`', key);
            }

            message = message.replace('Path ', '').replace(key,'').trim();
            error[key] = message;
        });

        return res.status(500).json(error); // or return next(error);
    }

    next();
};

And add it to your routes. For instance:

router.get('/batch', mongooseErrorHandler, (req, res, err) =>{
    ...
});

or if you are using next(err) in the middleware:

router.get('/batch', mongooseErrorHandler, (req, res, err) =>{
    if (err) res.status(500).json(err);
    ...
});
about 4 years ago · Santiago Trujillo 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