Skip to content

Commit 06c152b

Browse files
committed
code version 1.1.0
1 parent af5cf12 commit 06c152b

18 files changed

+1433
-654
lines changed

.eslintrc.json

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
{
2+
"root": true,
3+
"env": {
4+
"commonjs": true,
5+
"es6": true,
6+
"node": true,
7+
"jest": true
8+
},
9+
"extends": "eslint:recommended",
10+
"parserOptions": {
11+
"ecmaVersion": 2018,
12+
"sourceType": "module",
13+
"ecmaFeatures": {
14+
"modules": true,
15+
"experimentalObjectRestSpread": true
16+
}
17+
},
18+
"rules": {
19+
"indent": ["error", 2, { "SwitchCase": 1 }],
20+
"semi": ["error", "always"],
21+
"quotes": ["error", "single", { "avoidEscape": true }],
22+
"no-var": "error",
23+
"no-unused-vars": ["error", { "argsIgnorePattern": "next" }],
24+
"no-console": ["error"],
25+
"func-style": ["error", "declaration", { "allowArrowFunctions": true }],
26+
"object-curly-spacing": ["error", "always"],
27+
"comma-spacing": ["error", { "before": false, "after": true }],
28+
"key-spacing": ["error", { "beforeColon": false }],
29+
"no-constant-condition": ["error", { "checkLoops": false }],
30+
"quote-props": ["error", "as-needed"],
31+
"no-prototype-builtins": [0],
32+
"require-atomic-updates": [0]
33+
},
34+
"ignorePatterns": ["example"]
35+
}

.gitignore

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
globalConfig.json
21
node_modules

README.md

Lines changed: 263 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,269 @@
11
# Mongoose Validation Failed Handler
22

3-
## Usage
3+
## Install
44

5-
```javascripts
5+
```bash
6+
npm i mongoose-validation-error-message-handler
7+
```
8+
9+
## Usages
10+
11+
### Example 1 simple
12+
13+
```javascript
14+
const mongoose = require('mongoose');
15+
const mongooseErrorHandler = require('mongoose-validation-error-message-handler');
16+
17+
const schema = new mongoose.Schema({
18+
name: {
19+
type: String,
20+
required: true,
21+
},
22+
});
23+
24+
const model = mongoose.model('person', schema);
25+
26+
const object = new model({ name: 'a' });
27+
object.save(function (err, doc) {
28+
if (err) {
29+
const error = mongooseErrorHandler(err);
30+
console.log(error);
31+
/**
32+
* Error [MongooseValidatorError]: "name" is required
33+
* message: "name" is required
34+
* name: 'MongooseValidatorError',
35+
* path: 'name',
36+
* kind: 'unique',
37+
* value: "a"
38+
*/
39+
}
40+
});
41+
```
42+
43+
### Example 2 custom messages
44+
45+
```javascript
46+
const mongoose = require('mongoose');
47+
const mongooseErrorHandler = require('mongoose-validation-error-message-handler');
48+
49+
const schema = new mongoose.Schema({
50+
name: {
51+
type: String,
52+
},
53+
});
54+
55+
const model = mongoose.model('person', schema);
56+
57+
const object = new model({ name: {} });
58+
object.save(function (err, doc) {
59+
if (err) {
60+
const error = mongooseErrorHandler(err, {
61+
messages: {
62+
string: '{path} must be a string'
63+
}
64+
});
65+
console.log(error);
66+
/**
67+
* Error [MongooseValidatorError]: name must be a string
68+
* message: name must be a string
69+
* name: 'MongooseValidatorError',
70+
* path: 'name',
71+
* kind: 'string',
72+
* value: {}
73+
*/
74+
}
75+
});
76+
```
77+
78+
### Example 3 paths origin message
79+
80+
```javascript
81+
const mongoose = require('mongoose');
82+
const mongooseErrorHandler = require('mongoose-validation-error-message-handler');
83+
84+
const schema = new mongoose.Schema({
85+
name: {
86+
type: String,
87+
required: true,
88+
},
89+
});
90+
91+
const model = mongoose.model('person', schema);
92+
93+
const object = new model({});
94+
object.save(function (err, doc) {
95+
if (err) {
96+
const error = mongooseErrorHandler(err, {
97+
path: {
98+
name: { origin: true },
99+
nameX: { origin: true, kind: 'maxlength' },
100+
}
101+
});
102+
console.log(error);
103+
/**
104+
* person validation failed: name: Path `name` is required.
105+
*/
106+
}
107+
});
108+
```
109+
110+
### Example 4 paths custom messages
111+
112+
```javascript
113+
const mongoose = require('mongoose');
114+
const mongooseErrorHandler = require('mongoose-validation-error-message-handler');
115+
116+
const schema = new mongoose.Schema({
117+
name: {
118+
type: String,
119+
required: true,
120+
},
121+
});
122+
123+
const model = mongoose.model('person', schema);
124+
125+
const object = new model({});
126+
object.save(function (err, doc) {
127+
if (err) {
128+
const error = mongooseErrorHandler(err, {
129+
path: {
130+
name: { message: 'name is required' },
131+
nameX: { message: 'name length must be less than or equal to {maxlength} characters long', kind: 'maxlength' },
132+
}
133+
});
134+
console.log(error);
135+
/**
136+
* Error [MongooseValidatorError]: name is required
137+
* name: 'MongooseValidatorError',
138+
* path: 'name',
139+
* kind: 'required',
140+
* value: undefined
141+
*/
142+
}
143+
});
144+
```
145+
146+
### Example 5 unique
147+
You will need to install package `mongoose-unique-validator` first.
148+
149+
```javascript
150+
const mongoose = require('mongoose');
151+
const uniqueValidator = require('mongoose-unique-validator');
152+
const mongooseErrorHandler = require('mongoose-validation-error-message-handler');
153+
154+
mongoose.Promise = Promise;
155+
mongoose.connect('mongodb://localhost/example', {
156+
useNewUrlParser: true,
157+
useUnifiedTopology: true,
158+
});
159+
160+
mongoose.plugin(uniqueValidator);
161+
162+
const schema = new mongoose.Schema({
163+
name: {
164+
type: String,
165+
unique: true,
166+
},
167+
});
168+
169+
const model = mongoose.model('person', schema);
170+
171+
const object = new model({ name: 'a' });
172+
object.save(function (err, doc) {
173+
if (err) {
174+
const error = mongooseErrorHandler(err);
175+
console.log(error);
176+
/**
177+
* Error [MongooseValidatorError]: "name" is already exists
178+
* name: 'MongooseValidatorError',
179+
* path: 'name',
180+
* kind: 'unique',
181+
* value: "a"
182+
*/
183+
}
184+
});
185+
```
186+
187+
### Example 6 server express
188+
189+
```javascript
190+
const express = require('express');
191+
const mongoose = require('mongoose');
6192
const mongooseErrorHandler = require('mongoose-validation-error-message-handler');
7193

8-
const error = mongooseErrorHandler(mongoose.Error.ValidationError, {
9-
messages: {
10-
[kind]: String
11-
},
12-
paths: {
13-
[path]: Object
14-
}
194+
mongoose.Promise = Promise;
195+
mongoose.connect('mongodb://localhost/example', {
196+
useNewUrlParser: true,
197+
useUnifiedTopology: true,
15198
});
16-
```
199+
200+
const schema = new mongoose.Schema({
201+
name: {
202+
type: String,
203+
required: true,
204+
},
205+
});
206+
207+
const model = mongoose.model('person', schema);
208+
209+
const app = express();
210+
app.use(express.json());
211+
212+
app.post('/', async (req, res, next) => {
213+
try {
214+
const object = await model.create(req.body);
215+
res.json(object);
216+
} catch (error) {
217+
next(error)
218+
}
219+
});
220+
221+
// catch 404 and forward to error handler
222+
app.use((req, res, next) => {
223+
const err = new Error('Not Found');
224+
err.status = 404;
225+
next(err);
226+
});
227+
228+
// error handler
229+
app.use((err, req, res) => {
230+
let convertedError = mongooseErrorHandler(err);
231+
res.status(convertedError.status || 500);
232+
res.json({ message: convertedError.message });
233+
});
234+
235+
app.listen(3000)
236+
```
237+
238+
## Options
239+
240+
### messages
241+
242+
| Kind | Properties | Message | SchemaTypeOptions
243+
|------------------------|---------------|
244+
| base | `path`, `value` | {path} is invalid |
245+
| boolean | `path`, `value` | {path} must be a boolean | type |
246+
| buffer | `path`, `value` | {path} must be a buffer | type |
247+
| date | `path`, `value` | {path} must be a date | type |
248+
| date.max | `path`, `value`, `max` | {path} must be less than or equal to {max} | max |
249+
| date.min | `path`, `value`, `min` | {path} must be greater than or equal to {min} | min |
250+
| enum | `path`, `value`, `enumValues` | {path} is invalid | enum |
251+
| maxlength | `path`, `value`, `maxlength` | {path} length must be less than or equal to {maxlength} characters long | maxlength |
252+
| minlength | `path`, `value`, `minlength` | {path} length must be at least {minlength} characters long | minlength |
253+
| map | `path`, `value` | {path} must be a Map | type |
254+
| number | `path`, `value` | {path} must be a number | type |
255+
| number.max | `path`, `value`, `max` | {path} must be greater than or equal to {max} | max |
256+
| number.min | `path`, `value`, `min` | {path} must be less than or equal to {min} | min |
257+
| objectId | `path`, `value` | {path} must be a objectId | type |
258+
| regexp | `path`, `value`, `regexp` | {path} format is invalid | match |
259+
| required | `path`, `value` | {path} is required | required |
260+
| string | `path`, `value` | {path} must be a string | type |
261+
| unique | email '[email protected]' already exists. | unique |
262+
| validate | `path`, `value`, `enumValues` | {path} is invalid | validate |
263+
264+
### paths
265+
266+
`path`: String
267+
- `original`: Boolean,
268+
- `kind`: String,
269+
- `message`: String

example/custom-messages.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const mongoose = require('mongoose');
2+
const mongooseErrorHandler = require('../');
3+
4+
const schema = new mongoose.Schema({
5+
name: {
6+
type: String,
7+
required: true,
8+
},
9+
});
10+
11+
const model = mongoose.model('person', schema);
12+
13+
const messages = {
14+
base: '{path} is invalid',
15+
required: '{path} is required',
16+
enum: '{path} is invalid',
17+
validate: '{path} is invalid',
18+
unique: '{path} is already exists',
19+
boolean: '{path} must be a boolean',
20+
buffer: '{path} must be a buffer',
21+
objectId: '{path} must be a objectId',
22+
map: '{path} must be a Map',
23+
string: '{path} must be a string',
24+
maxlength: '{path} length must be less than or equal to {maxlength} characters long',
25+
minlength: '{path} length must be at least {minlength} characters long',
26+
regexp: '{path} format is invalid',
27+
number: '{path} must be a number',
28+
'number.max': '{path} must be greater than or equal to {max}',
29+
'number.min': '{path} must be less than or equal to {min}',
30+
date: '{path} must be a date',
31+
'date.max': '{path} must be less than or equal to {max}',
32+
'date.min': '{path} must be greater than or equal to {min}',
33+
}
34+
35+
const object = new model({});
36+
object.save(function (err, doc) {
37+
if (err) {
38+
const error = mongooseErrorHandler(err, { messages });
39+
console.log(error);
40+
/**
41+
* Error [MongooseValidatorError]: name is required
42+
* name: 'MongooseValidatorError',
43+
* path: 'name',
44+
* kind: 'required',
45+
* value: undefined
46+
*/
47+
}
48+
});

0 commit comments

Comments
 (0)