From 3f43399b1190318662fd9387ec8a499574a9b6bc Mon Sep 17 00:00:00 2001 From: Charles Dang Date: Tue, 29 Oct 2019 06:00:01 +1100 Subject: [PATCH] Better error messages when unique validation fails --- .changeset/three-wolves-prove.md | 5 +++++ packages/adapter-mongoose/lib/adapter-mongoose.js | 5 ++++- packages/adapter-mongoose/package.json | 1 + 3 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 .changeset/three-wolves-prove.md diff --git a/.changeset/three-wolves-prove.md b/.changeset/three-wolves-prove.md new file mode 100644 index 00000000000..9ee93a34f53 --- /dev/null +++ b/.changeset/three-wolves-prove.md @@ -0,0 +1,5 @@ +--- +'@keystonejs/adapter-mongoose': patch +--- + +Deployed mongoose-unique-validator for a more readable error message when unique checks fail diff --git a/packages/adapter-mongoose/lib/adapter-mongoose.js b/packages/adapter-mongoose/lib/adapter-mongoose.js index 1a04c706b17..e00615a60cc 100644 --- a/packages/adapter-mongoose/lib/adapter-mongoose.js +++ b/packages/adapter-mongoose/lib/adapter-mongoose.js @@ -1,4 +1,6 @@ const mongoose = require('mongoose'); +const uniqueValidator = require('mongoose-unique-validator'); + const pSettle = require('p-settle'); const { escapeRegExp, @@ -28,6 +30,7 @@ class MongooseAdapter extends BaseKeystoneAdapter { if (debugMongoose()) { this.mongoose.set('debug', true); } + this.mongoose.plugin(uniqueValidator); this.listAdapterClass = this.listAdapterClass || this.defaultListAdapterClass; } @@ -184,7 +187,7 @@ class MongooseListAdapter extends BaseListAdapter { _update(id, data) { // Avoid any kind of injection attack by explicitly doing a `$set` operation // Return the modified item, not the original - return this.model.findByIdAndUpdate(id, { $set: data }, { new: true }); + return this.model.findByIdAndUpdate(id, { $set: data }, { new: true, runValidators: true, context: 'query' }); } _findAll() { diff --git a/packages/adapter-mongoose/package.json b/packages/adapter-mongoose/package.json index 5ab3f7e2b24..5f2a2e1d917 100644 --- a/packages/adapter-mongoose/package.json +++ b/packages/adapter-mongoose/package.json @@ -16,6 +16,7 @@ "@sindresorhus/slugify": "^0.6.0", "lodash.omitby": "^4.6.0", "mongoose": "^5.7.7", + "mongoose-unique-validator": "^2.0.3", "p-settle": "^3.1.0", "pluralize": "^7.0.0" }