mongoose-beautiful-unique-validation icon indicating copy to clipboard operation
mongoose-beautiful-unique-validation copied to clipboard

Custom message not working

Open rhecl opened this issue 7 years ago • 9 comments

Hello,

I have the following schema:

const mongoose = require('mongoose');
const beautifyUnique = require('mongoose-beautiful-unique-validation');

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    lowercase: true,
    required: true,
    unique: 'A user with that e-mail already exists',
  },
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
});

UserSchema.plugin(beautifyUnique);

module.exports = mongoose.model('User', UserSchema, 'Users');

When I try to create a document with a duplicate e-mail, I don't get the custom message, instead I only get the following:

{ ValidationError: Validation failed
    at ValidationError.inspect (node_modules/mongoose/lib/error/validation.js:56:24)
    at ValidationError.deprecated (internal/util.js:70:15)
    at formatValue (util.js:466:31)
    at inspect (util.js:327:10)
    at Object.formatWithOptions (util.js:181:12)
    at Console.(anonymous function) (console.js:188:15)
    at Console.log (console.js:199:31)
    at errorHandler (/middleware/errorHandler.js:2:11)
    at dispatch (/node_modules/koa-compose/index.js:42:32)
    at next (/node_modules/koa-compose/index.js:43:18)
    at dispatch (/node_modules/koa-router/lib/router.js:332:32)
    at dispatch (/node_modules/koa-compose/index.js:42:32)
    at next (/node_modules/koa-compose/index.js:43:18)
    at dispatch (/node_modules/koa-router/lib/router.js:332:32)
    at dispatch (/node_modules/koa-compose/index.js:42:32)
    at next (/node_modules/koa-compose/index.js:43:18)
  errors: {},
  _message: 'Validation failed',
  name: 'ValidationError' }

I am using mongoose 5.0.13 and mongoose-beautiful-unique-validation 7.1.1.

Am I missing anything?

rhecl avatar Jun 08 '18 12:06 rhecl

Seems there is a problem with the regexp... :(

chumager avatar Jun 20 '18 16:06 chumager

Hello! Is this problem fixed? I have a similar situation, but the output differs a little:

{
    "errors": {},
    "_message": "Validation failed",
    "message": "Validation failed",
    "name": "ValidationError"
}

My schema looks like this:

const schema = new mongoose.Schema({
    // other properties
    email: { type: String, required: true, unique: 'Email must be unique: ({VALUE})' },
});

schema.plugin(beautifyUnique);

NoMercy235 avatar Jan 04 '19 15:01 NoMercy235

Hello! Is this problem fixed? I have a similar situation, but the output differs a little:

{
    "errors": {},
    "_message": "Validation failed",
    "message": "Validation failed",
    "name": "ValidationError"
}

My schema looks like this:

const schema = new mongoose.Schema({
    // other properties
    email: { type: String, required: true, unique: 'Email must be unique: ({VALUE})' },
});

schema.plugin(beautifyUnique);

i got the same problem

Maxtermax avatar Feb 12 '19 16:02 Maxtermax

I did tries with different version of this plugin and the issue seems to be present in mongo version 3.6 to up, with mongo 3.4 works!! but my solution was drop the plugin and focus in parse the error throwed by mongodb and so base on the example provide in the mongoosejs 5 website i did this code mimic the exact same response of this plugin.

UsersSchema.post("save", function (error, doc, next) {
  let duplicateError = error.name === "MongoError" && error.code === 11000;
  if (duplicateError) {
    let result = {
      name: "ValidationError",
      message: "Model validation failed",
      errors: {}
    }
    //Object.keys(this._doc) = ["email", "name", "password", ......]
    Object.keys(this._doc).forEach(path => {
      let isDuplicate = error.errmsg.includes(`$${path}_1`);//match with $email_1
      //Check if any attribute of the document is included in the error message as an unique field example:
      //11000 E11000 duplicate key error index: mydb.users.$email_1  dup key: { : "[email protected]" }
      if (isDuplicate) {
        let value = this._doc[path];
        result.errors[path] = {
          name: "ValidatorError",
          kind: "unique",
          message: `Path ${path} (${value}) is not unique.`,
          path,
          value
        }
      }
    })    
    next(result);
  } else {
    next()
  }
})

So as long mongoose return the error name as MongoError an the code as 11000 for duplicate values it should work in any version.

Maxtermax avatar Feb 13 '19 00:02 Maxtermax

Having the same problem here in my tests using mongodb-memory-server at least. Instead of returning my unique message it just returns.

{ ValidationError: Validation failed at ValidationError.Object..ValidationError.inspect (/node_modules/mongoose/lib/error/validation.js:59:24) at formatValue (internal/util/inspect.js:521:31) at inspect (internal/util/inspect.js:196:10) at formatWithOptions (util.js:84:12) at format (util.js:72:10) at CustomConsole.log (/node_modules/jest-util/build/CustomConsole.js:156:41) at Object.log (/database/user.test.js:81:17) at processTicksAndRejections (internal/process/next_tick.js:81:5) errors: {}, _message: 'Validation failed', name: 'ValidationError' }

Mongoose version: 5.4.10

ntrabue avatar Mar 15 '19 14:03 ntrabue

Is there any update on this issue?

AdamBCo avatar Apr 05 '19 14:04 AdamBCo

Any Update?

trylovetom avatar Jun 21 '19 15:06 trylovetom

The bug is still there <3. (at least for MySQL)

TheMarshalMole avatar Oct 22 '20 07:10 TheMarshalMole

hey @matteodelabre are you still maintaining this library?

tubbo avatar Feb 14 '22 17:02 tubbo