Giter Site home page Giter Site logo

matteodelabre / mongoose-beautiful-unique-validation Goto Github PK

View Code? Open in Web Editor NEW
117.0 8.0 40.0 199 KB

Plugin for Mongoose that turns duplicate errors into regular Mongoose validation errors

License: MIT License

JavaScript 100.00%
mongoose duplicates schema errors validation plugin

mongoose-beautiful-unique-validation's People

Contributors

bohdantkachenko avatar bvyask avatar infosnap-build avatar matteodelabre avatar misshula avatar nicksellen avatar niftylettuce avatar saviio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongoose-beautiful-unique-validation's Issues

Cannot get the custom message

I have this User schema:

import mongoose from 'mongoose'
import bcrypt from 'bcrypt-nodejs'
import beautifyUnique from 'mongoose-beautiful-unique-validation'

let UserSchema = mongoose.Schema({
  email: {
    type: String,
    required: [true, 'You need an email!'],
    validate: {
      validator: v => {
        return /^[A-Za-z0-9](([_.-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([.-]?[a-zA-Z0-9]+)*).([A-Za-z]{2,})$/.test(v)
      },
      message: "{VALUE} isn't valid!",
    },
    index: {
      unique: 'That email alredy exists!' // Here!
    }
  },
  password: {
    type: String,
    required: [true, 'You need a pasword!']
  }
})

UserSchema.statics = {
  generateHash: function (password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null)
  }
}

UserSchema.methods = {
  validPassword: function (password) {
    return bcrypt.compareSync(password, this.password)
  }
}

UserSchema.plugin(beautifyUnique)

let User = mongoose.model('User', UserSchema)

export default User

I'm unit testing my code, and when I try to save a user with a duplicated email like this:

async () => {
  let data = {
    email: '[email protected]',
    password: 'password'
  }

  let user1 = new models.User(data)
  try {
    await user1.save()
  } catch(err) {
    console.log('user1 error')
    console.log(err)
  }
  let user2 = new models.User(data)
  try {
    await user2.save()
  } catch(err) {
    console.log('user2 error')
    console.log(err)
  }

I get this error object:

user2 error
{ ValidationError: Validator failed for path `email` with value `[email protected]`
    at MongooseError.ValidationError (C:\[...]\backend\node_modules\mongoose\lib\error\validation.js:22:11)
    at C:\[...]\backend\node_modules\mongoose-beautiful-unique-validation\index.js:99:31
    at tryCallOne (C:\[...]\backend\node_modules\promise\lib\core.js:37:12)
    at C:\[...]\backend\node_modules\promise\lib\core.js:123:15
    at flush (C:\[...]\backend\node_modules\asap\raw.js:50:29)
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
  message: 'Validation failed',
  name: 'ValidationError',
  errors:
   { email:
      { Validator failed for path `email` with value `[email protected]`
          at MongooseError.ValidatorError (C:\[...]\backend\node_modules\mongoose\lib\error\validator.js:24:11)
          at C:\[...]\backend\node_modules\mongoose-beautiful-unique-validation\index.js:89:43
          at Array.forEach (native)
          at C:\[...]\backend\node_modules\mongoose-beautiful-unique-validation\index.js:77:40
          at tryCallOne (C:\[...]\backend\node_modules\promise\lib\core.js:37:12)
          at C:\[...]\backend\node_modules\promise\lib\core.js:123:15
          at flush (C:\[...]\backend\node_modules\asap\raw.js:50:29)
          at _combinedTickCallback (internal/process/next_tick.js:67:7)
          at process._tickCallback (internal/process/next_tick.js:98:9)
        message: 'Validator failed for path `email` with value `[email protected]`',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'Duplicate value',
        path: 'email',
        value: '[email protected]' } } }

And here I can't find the message I placed in the Schema 😢

Mongoose unique error is now a MongoServerError not MongoError

Hello,

From mongoose version 6 onwards, MongoError has been changed to MongoServerError. I think mongoose-beautiful-unique-validation plugin is not working for mongoose >= 6 version due to this change, as in the isUniqueError function just err.name === 'BulkWriteError' || err.name === 'MongoError' is checked.

I suggest adding MongoServerError to this condition. In case of any doubt, I leave the error log using mongoose 7.0.4:

MongoServerError: E11000 duplicate key error collection: followupusers index: email_1 dup key: { email: "[email protected]" } at node_modules\mongodb\lib\operations\insert.js:50:33 at node_modules\mongodb\lib\cmap\connection_pool.js:327:25 at node_modules\mongodb\lib\sdam\server.js:207:17 at handleOperationResult (node_modules\mongodb\lib\sdam\server.js:323:20) at Connection.onMessage (node_modules\mongodb\lib\cmap\connection.js:213:9) at MessageStream.<anonymous> (node_modules\mongodb\lib\cmap\connection.js:59:60) at MessageStream.emit (node:events:512:28) at processIncomingData (node_modules\mongodb\lib\cmap\message_stream.js:124:16) at MessageStream._write (node_modules\mongodb\lib\cmap\message_stream.js:33:9) at writeOrBuffer (node:internal/streams/writable:392:12) { index: 0, code: 11000, keyPattern: { email: 1 }, keyValue: { email: '[email protected]' }, [Symbol(errorLabels)]: Set(0) {} }

Thanks in advance.

Tests are randomly failing

Probably due to some race condition, the tests sometimes fail with the following message:

✖ should not save duplicate successfully

meaning that both the original instance and the duplicate are saved in the database (or at least reported as saved). We should track down if the issue comes from the tests, from MongoDB or from the library.

This also explains why the CI sometimes fail.

How to reproduce

In Bash, issue the test command until it fails (can take several minutes):

while npm test; do :; done

Plugin validating unique on a non unique field

I have the following schema

const   mongoose        = require('mongoose'),
        uniqueValidator  = require('mongoose-beautiful-unique-validation'),
        Schema          = mongoose.Schema;

const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

const ClientSchema = new Schema({
    name: {
        type: String,
        required: [true, 'Campo nombre es requerido'],
    },
    email: {
        type: String,
        unique: 'Ya existe un cliente registrado con el correo: \'{VALUE}\'',
        required: [true, 'Campo email es requerido'],
        validate:  {
            validator: v => re.test(v),
            message: props => `Ingrese un correo valido`
        }
    },
    address: {
        type: String,
        required: [true, 'Campo dirección es requerido'],
        validate:  {
            validator: v => v.length >= 5,
            message: props => `Ingrese una dirección valida`
        }
    },
    phone : {
        type: String,
        unique: 'Ya existe un cliente registrado con el telefono: \'{VALUE}\'',
        required: [true, 'Campo telefono es requerido'],
        validate:  {
            validator: v => !isNaN(v) && v.length >= 7,
            message: props => `'${props.value}' no es un número telefónico válido`
        }
    }
});
ClientSchema.plugin(uniqueValidator);

The problem is, that mongoose-beautiful-unique-validation is validating address as an unique field when I never set the unique property on that field.

Unique custom message on nested objects.

The custom message doesn't work when using it on a nested object within a mongoose schema.

Ex:

const userSchema = new Schema({
    /*
    |----------------------
    | Structure
    |----------------------
    */
    general: {
        firstName: {
            type: String,
            required: true
        },

        lastName: {
            type: String,
            required: true
        },

        email: {
            type: String,
            required: true,
            unique: 'Mailen du angav finns redan.'
        },
   }
});

Do I need to stop using nested objects or is there another way?

No Update hook?

There is missing update hook on last version. Intended? When I try findOneAndUpdate, it works.

"mongoose": "^4.6.5",
"mongoose-beautiful-unique-validation": "^5.1.1",

TypeError for plugin

[email protected]
[email protected]

I get the following error, when calling the plugin method for my schema:

TypeError: fn is not a function
    at Schema.plugin (/node_modules/mongoose/lib/schema.js:1139:3)
    at Object.<anonymous> (/app/models/user.js:211:12)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)

Working with mongoose v6

This is rather a question than a bug report. We are planning to migrate mongoose v5 to v6 but we are not 100% sure if this package does provide support for v6. Package.json references mongoose >=4 for deps and for devDeps v5.

Before putting effort in this and later finding out that something like #68 is a showstopper, we would like to know if anyone is running this package with mongoose v6.

Thanks in advance!

Type should be lowercase underscored "duplicate_value"

As similar to other types of enum, max, min, and required - we should have either the type be "unique" or "duplicate_value" instead of "Duplicate value" (it is not consistent with Mongoose standard types that already exist for Schema props.

Doesn't work with mongoose 5.12.5 and nestjs

I tried using globally and sat directly in a schema:

@Prop({
    raw: {
      index: true,
      required: true,
      unique: 'Email ({VALUE}) is already registered',
      type: String,
    },
  })
  public email: string;
@Prop({
      index: true,
      required: true,
      unique: 'Email ({VALUE}) is already registered',
      type: String
  } as PropOptions<any>)
  public email: string;
[Nest] 23477   - 04/22/2021, 1:22:02 AM   [ExceptionsHandler] Validation failed +1471ms
ValidationError: Validation failed
    at /Volumes/dev/organic/dist/main.js:1975:31
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

Support Uniqueness on ObjectId fields

Hi,
I have several compound indexes and some are like this one :

var clientSchema = new Schema({
  group: {type: Schema.Types.ObjectId, required: true},
  filemd5 : {type: String},
  status: {type: String}
});

clientSchema.index({filemd5: 1, group: 1}, {unique: true});

Unfortunately, using your library when it tries to beautify the duplicate message error I get this :

[Error: mongoose-beautiful-unique-validation error: cannot parse duplicated values to a meaningful value. Parsing error: Unexpected token O]

The original error message is the following :
{ [MongoError: E11000 duplicate key error collection: visage.candidate-submission index: candidateEmail_1_job_1 dup key: { : "md5file", : ObjectId('284028532053528') }]

My guess is that it happens because you try to parse the { : "md5file", : ObjectId('284028532053528') } part with as a JSON string. Unfortunately it goes wrong for the ObjectId because this is BSON notation not JSON.
Can we expect a fix for this ?

Thank you.

can't get it working with 4.4.12

I'm still getting default mongoose messages;

{ [MongoError: E11000 duplicate key error index: buharmetre-development.users.$username_1 dup key: { : "Bonesoul" }]
  name: 'MongoError',
  message: 'E11000 duplicate key error index: buharmetre-development.users.$username_1 dup key: { : "Bonesoul" }',
  driver: true,
  code: 11000,
  index: 0,
  errmsg: 'E11000 duplicate key error index: buharmetre-development.users.$username_1 dup key: { : "Bonesoul" }',
  getOperation: [Function],
  toJSON: [Function],
  toString: [Function] }

and yes i've plugged it as a plugin already;

var beautifyUnique = require('mongoose-beautiful-unique-validation');
var UserSchema = new mongoose.Schema({
    username: { type: String, unique: true, trim: true, required: true },
    email: { type: String, unique: true, trim: true, required: true, lowercase: true }
});

UserSchema.plugin(beautifyUnique); // beatuify unique errors.

6.0.0 and mongoose 4.11.3

Getting an error when unique fails, it appears in the postHook function the doc is null, the error message looks correct. Didnt dive in too much yet , see attached screen with values that cause the error.
Error w/ 5.1.1

TypeError: Cannot use 'in' operator to search for 'collection' in null at beautify (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose-beautiful-unique-validation/index.js:61:22) at model.postHook (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose-beautiful-unique-validation/index.js:147:13) at next (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/kareem/index.js:149:14) at Kareem.execPost (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/kareem/index.js:197:3) at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/lib/model.js:217:35 at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/lib/model.js:150:9 at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/collection.js:535:20 at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/collection.js:669:14 at handleCallback (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/utils.js:120:56) at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:465:9 at handleCallback (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/utils.js:120:56) at resultHandler (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:413:5) at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:469:18 at _combinedTickCallback (internal/process/next_tick.js:95:7) at process._tickDomainCallback (internal/process/next_tick.js:198:9)
Error with 6.0.0 (and attached image)

TypeError: Cannot read property 'collection' of null at model.postHook (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose-beautiful-unique-validation/index.js:152:33) at next (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/kareem/index.js:149:14) at Kareem.execPost (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/kareem/index.js:197:3) at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/lib/model.js:217:35 at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/lib/model.js:150:9 at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/collection.js:535:20 at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/collection.js:669:14 at handleCallback (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/utils.js:120:56) at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:465:9 at handleCallback (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/utils.js:120:56) at resultHandler (/Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb/lib/bulk/unordered.js:413:5) at /Users/michaelmorris/AirTab/backend/airtab-app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:469:18 at _combinedTickCallback (internal/process/next_tick.js:95:7) at process._tickDomainCallback (internal/process/next_tick.js:198:9)

screen shot 2017-07-18 at 11 52 38 am

v5.1.0 raises validation errors to every other field

I have a schema with lots of fields and one of them is unique.

When you update values and then save(), if there's a duplication of that unique field, its validation error is raised fine, but every other field gets a validation error too.

This was introduced in v5.1.0. I think there's only tests involving simple schemas containing just unique fields. LoL

Error [TypeError: Cannot read property '1' of null]

The error is on the line 91.

valueRegex.exec(rawValues) return null.

I'm using the MongoDB shell version: 3.2.6 and [email protected]

I believe the text changed in the newest version of mongodb and regex can not run properly.

{ [MongoError: E11000 duplicate key error collection: pinaopen.players index: name_1 dup key: { : "Bruno Barros" }]
name: 'MongoError',
message: 'E11000 duplicate key error collection: pinaopen.players index: name_1 dup key: { : "Bruno Barros" }',
driver: true,
code: 11000,
index: 0,
errmsg: 'E11000 duplicate key error collection: pinaopen.players index: name_1 dup key: { : "Bruno Barros" }',
getOperation: [Function],
toJSON: [Function],
toString: [Function] }

Version 7.1.1 Doesn't work mongoose 6.0.9 && mongo version 4.2

error to string

MongoServerError: E11000 duplicate key error collection: test_db.users index: email_1 dup key: { email: "[email protected]" }
at /api/node_modules/mongodb/lib/operations/insert.js:51:33
at /api/node_modules/mongodb/lib/cmap/connection_pool.js:272:25
at handleOperationResult (/api/node_modules/mongodb/lib/sdam/server.js:363:9)
at MessageStream.messageHandler (/api/node_modules/mongodb/lib/cmap/connection.js:479:9)
at MessageStream.emit (events.js:314:20)
at processIncomingData (/api/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
at MessageStream._write (/api/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
at writeOrBuffer (_stream_writable.js:352:12)
at MessageStream.Writable.write (_stream_writable.js:303:10)
at Socket.ondata (_stream_readable.js:714:22) {
index: 0,
code: 11000,
keyPattern: { email: 1 },
keyValue: { email: '[email protected]' }
}

GitHub releases are missing

Looks like you may have forgotten to push your tags to GitHub after publishing to NPM. Having these tags/releases in GitHub helps developers reference code from exact versions they are using.

Also, it looks like your repository URL needs updating.

mongoose-beautiful-unique-validation schema tree traversal can reach Mongo driver through $$context

I recently ran into a problem with Mongoose 4: Somehow, mongoose-beautiful-unique-validation wound up looking at the Mongo driver's object, and _events on a Mongo "db" was an unusual JS value with no prototype.

It reached it through the following chain:
Schema tree ->
Child schema which was used as a subdocument on the document. This child schema was also used as a model ->
Field on the child schema ->
$$context (internal field) on the child schema ->
mongooseCollection ->
collection ->
s ->
db ->
_events

I can't reproduce it in a minimal test case, unfortunately— this only shows up inconsistently. It probably only shows up when Mongoose is in a specific state.

There are also infinite property chains present in collection, so even if we call Object.prototype.hasOwnProperty instead of tree.hasOwnProperty, the tree traversal can still run into problems.

I fixed it with this patch:
askspoke@6261837

but, I'm not sure if that's the best approach.

MBUV: 7.1.1
Mongoose: 4.11.11

💡 cache index information

If we can cache the index information in memory,
then we don't need to query indexes every time when an error occurs

better performance

Handle 11001 Errors

I did not see that this plugin handles 11001 errors from Mongo, which occur when violating a unique index constraint when saving an existing document. Is this something that was left out for a specific reason? I was thinking about using this plugin, but was not sure why this was left out. I could add this, but wanted to check first.

Custom messages not working

It appears there is a small bug / typo in the code relating to custom messages. I am also working on a fix for that. Should have a pull request soon.

Self-referenced schemas trigger an exception

Self-referenced schemas trigger an exception (max call stack size exceeded):

var zone = new Schema({
  name: {type: String, required: true},
  created_at: Date,
  updated_at: Date
});

zone.add({zones: [zone]});

Thank you.

Custom message not working

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?

Support for compound indexes

The current version appears to support unique keys however not complex unique keys.

Example

const mongoose = require('mongoose');
const beautifyUnique = require('../scripts/mongoose-beautiful-unique-validation');
const Schema = mongoose.Schema;

let modelSchema = new Schema({
  name: { type: String, required: true, max: 100 },
  serial: { type: String, required: true, max: 100 },
  foreignKey: { type: String, required: true, max: 100 },
  created: { type: Date, default: () => new Date() }
});

modelSchema .index({ foreignKey: 1, serial: 1 }, { unique: true });
modelSchema .plugin(beautifyUnique);

module.exports = mongoose.model('model', modelSchema );

Suggested

modelSchema .index({ foreignKey: 1, serial: 1 }, { unique: "'{VALUE}' is already in use" });

ValidationError contains empty errors property

Hi,
Using Mongo 3.2x with Mongoose 4.13x properly includes errors property where I can extract values.

Using Mongo 3.4x with Mongoose 4.13x does not include the errors property.

Is there an incompatibility I should be aware of?

Thanks!

Support `Model.create`

I want to mongoose-beautiful-unique-validation support mongoose.Model.create method, if you have time ,please fix this. thanks a lot.

Error Regex does not match all Mongo Error structures

Using Mongo version 3.2.4 installed on Ubuntu 14.04

It seems as if the errorRegex (index.js#L6) you are using does not match all structures of E11000 duplicate key errors.

For example: https://regex101.com/r/lA2dZ7/1


Error Regex

var errorRegex = /index:\s*.+?\.\$(\S*)\s*dup key:\s*\{(.*?)\}/;

Matching Error Structure

E11000 duplicate key error index: database-name.users.$username_1 dup key: { : "andrew" }

Non-matching Error Structure

E11000 duplicate key error collection: database-name.users index: username_1 dup key: { : "andrew" }

Validation not working

I had implemented basic mongoose validation first, then switch to mongoose-beautiful-unique-validation.
This does not seem to work. I'm getting this error instead:
{
"errors": {},
"_message": "Validation failed",
"name": "ValidationError"
}

Not getting errors as expected. Did I do something wrong: Following is my schema:

let collectionsSchema = new Schema({
'eventsId': [{
'type': Schema.Types.ObjectId,
'ref': 'events'
}],
'collectionName': {
'type': String,
'required': true,
'unique' : true,
'trim' : true
},
'collectionSubTitle': {
'type': String,
'trim' : true
},
'collectionImage': {
'type': String,
'required': true
},
'collectionImageType': {
'type': String,
'enum': ['Upload', 'Url'],
'required' : true
},
'showStatus': {
'type': String,
'enum': ['Published', 'Unpublished', 'Auto'],
'required': true,
'trim' : true
}
}, {
'timestamps': true
});

My mongoose version is : [email protected]

Global error

This is a open discussion about a particular line of code of the library:

beautify(
                error, collection, values,
                messages, options.defaultMessage
            )
                .then(next)
                .catch(function (beautifyError) {
                    setTimeout(function () {
                        throw new Error(
                            'mongoose-beautiful-unique-validation error: '
                            + beautifyError.stack
                        );
                    });
});

When beautify fails, its send a global error within a setTimeout() instead of propagating the error. Which lead to a crash.

Is this feature strongly required by this library, or should we just call next(aNewError) like this?

beautify(
                error, collection, values,
                messages, options.defaultMessage
            )
                .then(next)
                .catch((beautifyError) => next(beautifyError) );
});

Are all errors supposed to be returned?

Hi and thanks for the plugin!

From the documentation I understand that all the validation errors should come at once. However, it is returning one error only.

For example, I have two unique fields in my schema (username and email). If I try to create a document where neither username nor email are unique the response I get is only saying that the email is not unique. However if I change the email to something unique and leave the username as before, then I receive a response saying that the username is not unique.

Is this the intended behavior? Or should I be receiving one response with all the validation errors?

Thanks in advance!

Incorrect regex for compound keys

Hey, have a issues with this error message parsing E11000 duplicate key error index: heroku_4k0w7dhh.users.$email_1 dup key:.

Current regex parse this as: heroku_4k0w7dhh.users.$email_1.
Actually these are my collection indexes:

{ name_1: [ [ 'name', 1 ] ],
  email_1: [ [ 'email', 1 ] ],
  _id_: [ [ '_id', 1 ] ],
  phone_1: [ [ 'phone', 1 ] ] } 

As a result, I do not get a beautiful error.

💡display model name in error

In regular mongoose error, the default message shoud be ModelName validation failed

e.g.
{
"name": "ValidationError",
"message": "User Validation failed",
"errors": {
"name": {
"name":"ValidatorError",
"properties": {
"type": "Duplicate value",
"message": "Custom error message",
"path": "name",
"value": "John"
},
"message": "Custom error message",
"kind": "Duplicate value",
"path": "name",
"value": "John"
}
}
}

ValidationError contains empty errors property

I have a User mongoose schema with this property:

email: {
  type: String,
  required: 'email.blank',
  validate: emailValidator,
  unique: true
}

When I try and save a user I get a ValidationError however the errors property in ValidationError in empty. I have also tried this:

email: {
  type: String,
  required: 'email.blank',
  validate: emailValidator,
  unique: 'email.conflict'
}

However still the errors propert in ValidationError is empty. If I remove the unique property then everything works fine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.