Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.94k stars 3.84k forks source link

help on msg error #6817

Closed wesleysd1989 closed 6 years ago

wesleysd1989 commented 6 years ago

hello, i use mongoose on my project

i translated errors on mongoose to pt-br in code i need help to params unique = true, is possible i custon unique msg?

const mongoose = require('mongoose') //import framework on mongoDB comunication
const env = require('../../.env') //import variables on enviroment 
mongoose.Promise = global.Promise //configure depreciated promises on new mongoose framework
module.exports = mongoose.connect(env.stringDB,{ useNewUrlParser: true }) //export connection DB

//translate msg error to PT-BR
mongoose.Error.messages.general.required = "O atributo '{PATH}' é obrigatório."
mongoose.Error.messages.Number.min = 
    "O '{VALUE}' informado é menor que o limite mínimo de '{MIN}'."
mongoose.Error.messages.Number.max = 
    "O '{VALUE}' informado é maior que o limite máximo de '{MAX}'."
mongoose.Error.messages.String.enum = 
    "'{VALUE}' não é válido para o atributo '{PATH}'."

now i recive

{
    "name": "MongoError",
    "message": "E11000 duplicate key error index: teste.products.$title_1 dup key: { : \"teste\" }",
    "driver": true,
    "index": 0,
    "code": 11000,
    "errmsg": "E11000 duplicate key error index: teste.products.$title_1 dup key: { : \"teste\" }"
}

i need, exemple: "já existe '{VALUE}' cadastrado"

wesleysd1989 commented 6 years ago

in schema not work

const productSchema = new mongoose.Schema({
  title: { type: String, required: true, unique: [true, 'Esse produto já esta cadastrado!'] },
  description: { type: String, required: true },
  numberTickets: { type: Number, min: 1, required: true },
  images: [imgSchema],
  categories: [categoriesSchema],
  tickets: [ticketSchema]
})
Fonger commented 6 years ago

@wesleysd1989 http://mongoosejs.com/docs/validation.html#the-unique-option-is-not-a-validator

unique is not a validator so you can't use custom message there.

What you can do is to manually check for error.name === 'MongoError' && error.code === 11000 and throw a custom error.