-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcustom-paths.js
84 lines (78 loc) · 2.04 KB
/
custom-paths.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const mongoose = require('mongoose');
const mongooseErrorHandler = require('../');
const schema = new mongoose.Schema({
name: {
type: String,
required: true,
maxlength: 10
},
});
const model = mongoose.model('person', schema);
/* Example 1: Paths original message error */
const o1 = new model({});
o1.save(function (err, doc) {
if (err) {
const error = mongooseErrorHandler(err, {
paths: {
name: { original: true }
}
});
console.log(error);
/**
* person validation failed: name: Path `name` is required.
*/
}
});
/* Example 2: Paths kind original message error */
const o2 = new model({});
o2.save(function (err, doc) {
if (err) {
const error = mongooseErrorHandler(err, {
paths: {
name: { original: true, kind: 'required' }
}
});
console.log(error);
/**
* person validation failed: name: Path `name` is required.
*/
}
});
/* Example 3: Paths custom messages */
const o3 = new model({ name: 'aaaaaaaaaaa' });
o3.save(function (err, doc) {
if (err) {
const error = mongooseErrorHandler(err, {
paths: {
name: { message: 'name length must be less than or equal to {maxlength} characters long' }
}
});
console.log(error);
/**
* Error [MongooseValidatorError]: name ength must be less than or equal to 10 characters long
* name: 'MongooseValidatorError',
* path: 'name',
* kind: 'maxlength',
* value: 'aaaaaaaaaaa
*/
}
});
/* Example 4: Paths custom messages */
const o4 = new model({ name: 'aaaaaaaaaaa' });
o4.save(function (err, doc) {
if (err) {
const error = mongooseErrorHandler(err, {
paths: {
name: { kind: 'maxlength', message: 'name length must be less than or equal to {maxlength} characters long' }
}
});
console.log(error);
/**
* Error [MongooseValidatorError]: name ength must be less than or equal to 10 characters long
* name: 'MongooseValidatorError',
* path: 'name',
* kind: 'maxlength',
* value: 'aaaaaaaaaaa
*/
}
});