matteodelabre / mongoose-beautiful-unique-validation Goto Github PK
View Code? Open in Web Editor NEWPlugin for Mongoose that turns duplicate errors into regular Mongoose validation errors
License: MIT License
Plugin for Mongoose that turns duplicate errors into regular Mongoose validation errors
License: MIT License
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 😢
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.
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.
In Bash, issue the test command until it fails (can take several minutes):
while npm test; do :; done
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.
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?
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",
[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)
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!
Custom message detection in nested schema failed and throwing max call stack size exceeded
error.
RCA: Repeating schema instead of schema tree
Fix: Replace below code in line number 71.
var subtree = collectMessages(tree[key].tree);
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.
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)
It would be great to be able to plug this in to all schemas, by using the mongoose singleton .plugin method as documented here:
http://mongoosejs.com/docs/plugins.html
let mongoose = require('mongoose');
let beautifyUnique = require('mongoose-beautiful-unique-validation');
mongoose.plugin(beutifyUnique);
Gives blank error messages, everything else seems to work
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.
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.
Does not translate error when save is performed from findOneAndUpdate.
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)
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
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] }
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]' }
}
The test suite is failing on Travis, but is running as expected locally.
This might be due a discrepancy in the MongoDB setup.
Tests failing are those checking that saving duplicates generates errors.
https://travis-ci.org/matteodelabre/mongoose-beautiful-unique-validation/jobs/104286507
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.
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
One difference I've already noticed is some errors are returned as BulkWriteError
and not MongoError
.
Per an issue I filed at Automattic/mongoose#5534, our current usage of the global is not going to work. I am sending a PR in shortly to resolve this, and also update documentation until this issue is resolved.
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
Custom message detection in nested schema failed and throwing max call stack size exceeded
error.
RCA: Repeating schema instead of schema tree at line number 71
Fix: Replace below code at line number 71.
var subtree = collectMessages(tree[key].tree);
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.
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 (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.
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?
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" });
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!
Hello, please provide example for update of document.
I want to mongoose-beautiful-unique-validation support mongoose.Model.create method, if you have time ,please fix this. thanks a lot.
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" }
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]
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) );
});
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!
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.
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"
}
}
}
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.
MBUV no working validations with moongose:latest ( 5.7.0 )
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.