How to handle errors in Mongoose optimally

Asked

Viewed 437 times

2

I am starting to work with Mongodb + Mongoose and I am having problems dealing with the mistakes that Mongoose generates. One of the same is when there is a duplicate key for a parameter that should be unique. Ex:

Model (Usuariomodel)

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 model, Mongoose will not be able to save new documents that have the email repeated. This I could already understand, make work and see the answer within my application. Ex:

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

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 trying to save where email already exists, Mongoose does not bring me this in a friendly way. The message I received in the variable err of the above code was that:

{
    "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 a more "friendly" way for me to understand this mistake? the only way I thought was to do a specific treatment based on the parameter code from JSON that Mongoose returned me but so I would have to make a micro-library only error handling... It’s really the only way to treat it?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.