Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom message not working #54

Open
rhecl opened this issue Jun 8, 2018 · 9 comments
Open

Custom message not working #54

rhecl opened this issue Jun 8, 2018 · 9 comments

Comments

@rhecl
Copy link

rhecl commented Jun 8, 2018

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?

@chumager
Copy link

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

@NoMercy235
Copy link

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);

@Maxtermax
Copy link

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
Copy link

Maxtermax commented Feb 13, 2019

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.

@ntrabue
Copy link

ntrabue commented Mar 15, 2019

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

@AdamBCo
Copy link

AdamBCo commented Apr 5, 2019

Is there any update on this issue?

@trylovetom
Copy link

Any Update?

@TheMarshalMole
Copy link

TheMarshalMole commented Oct 22, 2020

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

@tubbo
Copy link

tubbo commented Feb 14, 2022

hey @matteodelabre are you still maintaining this library?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants