Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda