How to optimally handle errors in Mongoose

2

I'm starting to work with MongoDB + Mongoose and I'm having trouble dealing with the errors that mongoose generates. One of the same is when there is a duplicate key for a parameter that should be unique. Ex:

Model (UserModel)

const mongoose = require('mongoose');
const UsuarioSchema = new mongoose.Schema({
    email: {type: String,required: true,index: true},
    senha: {type: String,required: true},
    nome: { type: String, required: true}
});
const UsuarioModel = mongoose.model('Usuario', UsuarioSchema, 'Usuario');    

module.exports = UsuarioModel;

Using this template, mongoose will not be able to save new documents that have the email repeated. I've already been able to understand, make it work and see the answer within my application. Ex:

Code that saves the user on the ExpressJS (POST) route

UsuarioRoute.post('/', (req, res) => {
    let Usuario = new UsuarioModel(req.body);
    Usuario.save((err, Usuario) => {
        err ? res.status(400).send(err) : res.send('ok.');
    });
});

My problem is that when an error occurs (such as the save attempt where the email already exists, Mongoose does not bring it to me in a friendly way.) The message I received in the variable err of the code above was this:

{
    "code":11000,
    "index":0,
    "errmsg":"E11000 duplicate key error collection: foo.Usuario index: email_1 dup key: { : \"[email protected]\" }",
    "op":{
        "email":"[email protected]",
        "nome":"foo",
        "senha":"123",
    }
}

Is there any more "friendly" way of understanding this error? the only way I thought was to do a specific treatment based on the code parameter of JSON that Mongoose returned me but so I would have to do a single error-handling micro-library ... It really is the only way treat it?

    
asked by anonymous 03.04.2017 / 06:05

0 answers