forked from Automattic/mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.html
More file actions
560 lines (505 loc) · 41.3 KB
/
validation.html
File metadata and controls
560 lines (505 loc) · 41.3 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Mongoose v5.1.8-pre: Validation</title><link rel="apple-touch-icon" sizes="57x57" href="images/favicon/apple-icon-57x57.png"><link rel="apple-touch-icon" sizes="60x60" href="images/favicon/apple-icon-60x60.png"><link rel="apple-touch-icon" sizes="72x72" href="images/favicon/apple-icon-72x72.png"><link rel="apple-touch-icon" sizes="76x76" href="images/favicon/apple-icon-76x76.png"><link rel="apple-touch-icon" sizes="114x114" href="images/favicon/apple-icon-114x114.png"><link rel="apple-touch-icon" sizes="120x120" href="images/favicon/apple-icon-120x120.png"><link rel="apple-touch-icon" sizes="144x144" href="images/favicon/apple-icon-144x144.png"><link rel="apple-touch-icon" sizes="152x152" href="images/favicon/apple-icon-152x152.png"><link rel="apple-touch-icon" sizes="180x180" href="images/favicon/apple-icon-180x180.png"><link rel="icon" type="image/png" sizes="192x192" href="images/favicon/android-icon-192x192.png"><link rel="icon" type="image/png" sizes="32x32" href="images/favicon/favicon-32x32.png"><link rel="icon" type="image/png" sizes="96x96" href="images/favicon/favicon-96x96.png"><link rel="icon" type="image/png" sizes="16x16" href="images/favicon/favicon-16x16.png"><link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css" integrity="sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w" crossorigin="anonymous"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans"><link rel="stylesheet" href="/docs/css/github.css"><link rel="stylesheet" href="/docs/css/mongoose5.css"><link rel="apple-touch-icon" sizes="57x57" href="images/favicon/apple-icon-57x57.png"><link rel="apple-touch-icon" sizes="60x60" href="images/favicon/apple-icon-60x60.png"><link rel="apple-touch-icon" sizes="72x72" href="images/favicon/apple-icon-72x72.png"><link rel="apple-touch-icon" sizes="76x76" href="images/favicon/apple-icon-76x76.png"><link rel="apple-touch-icon" sizes="114x114" href="images/favicon/apple-icon-114x114.png"><link rel="apple-touch-icon" sizes="120x120" href="images/favicon/apple-icon-120x120.png"><link rel="apple-touch-icon" sizes="144x144" href="images/favicon/apple-icon-144x144.png"><link rel="apple-touch-icon" sizes="152x152" href="images/favicon/apple-icon-152x152.png"><link rel="apple-touch-icon" sizes="180x180" href="images/favicon/apple-icon-180x180.png"><link rel="icon" type="image/png" sizes="192x192" href="images/favicon/android-icon-192x192.png"><link rel="icon" type="image/png" sizes="32x32" href="images/favicon/favicon-32x32.png"><link rel="icon" type="image/png" sizes="96x96" href="images/favicon/favicon-96x96.png"><link rel="icon" type="image/png" sizes="16x16" href="images/favicon/favicon-16x16.png"><link rel="manifest" href="images/favicon/manifest.json"><meta name="msapplication-TileColor" content="#ffffff"><meta name="msapplication-TileImage" content="images/favicon/ms-icon-144x144.png"><meta name="theme-color" content="#ffffff"></head><body><div id="layout"><div id="mobile-menu"><a id="menuLink" href="#menu" class="menu-link"><span></span></a><div id="mobile-logo-container"><a href="/"><img id="logo" src="/docs/images/mongoose5_62x30_transparent.png"><span class="logo-text">mongoose</span></a></div></div><div id="menu"><div class="pure-menu"><div id="logo-container" class="pure-menu-heading"><a href="/"><img id="logo" src="/docs/images/mongoose5_62x30_transparent.png"><span class="logo-text">mongoose</span></a></div><ul class="pure-menu-list"><li class="pure-menu-horizontal pure-menu-item pure-menu-has-children pure-menu-allow-hover version"><a href="#" class="pure-menu-link">Version 5.1.8-pre</a><ul class="pure-menu-children"><li class="pure-menu-item"><a href="/docs/4.x" class="pure-menu-link">Version 4.13.14</a></li><li class="pure-menu-item"><a href="/docs/3.8.x" class="pure-menu-link">Version 3.8.40</a></li></ul></li><li class="pure-menu-item"><a href="/docs/index.html" class="pure-menu-link">Quick Start</a></li><li class="pure-menu-item"><a href="/docs/guides.html" class="pure-menu-link">Guides</a></li><li class="pure-menu-item sub-item"><a href="/docs/guide.html" class="pure-menu-link">Schemas</a></li><li class="pure-menu-item sub-item"><a href="/docs/schematypes.html" class="pure-menu-link">SchemaTypes</a></li><li class="pure-menu-item sub-item"><a href="/docs/connections.html" class="pure-menu-link">Connections</a></li><li class="pure-menu-item sub-item"><a href="/docs/models.html" class="pure-menu-link">Models</a></li><li class="pure-menu-item sub-item"><a href="/docs/documents.html" class="pure-menu-link">Documents</a></li><li class="pure-menu-item sub-item"><a href="/docs/subdocs.html" class="pure-menu-link">Subdocuments</a></li><li class="pure-menu-item sub-item"><a href="/docs/queries.html" class="pure-menu-link">Queries</a></li><li class="pure-menu-item sub-item"><a href="/docs/validation.html" class="pure-menu-link">Validation</a></li><li class="pure-menu-item sub-item"><a href="/docs/middleware.html" class="pure-menu-link">Middleware</a></li><li class="pure-menu-item sub-item"><a href="/docs/populate.html" class="pure-menu-link">Populate</a></li><li class="pure-menu-item sub-item"><a href="/docs/discriminators.html" class="pure-menu-link">Discriminators</a></li><li class="pure-menu-item sub-item"><a href="/docs/plugins.html" class="pure-menu-link">Plugins</a></li><li class="pure-menu-item"><a href="/docs/api.html" class="pure-menu-link">API</a></li><li class="pure-menu-item sub-item"><a href="/docs/api.html#mongoose_Mongoose" class="pure-menu-link">Mongoose</a></li><li class="pure-menu-item sub-item"><a href="/docs/api.html#Schema" class="pure-menu-link">Schema</a></li><li class="pure-menu-item sub-item"><a href="/docs/api.html#Connection" class="pure-menu-link">Connection</a></li><li class="pure-menu-item sub-item"><a href="/docs/api.html#Document" class="pure-menu-link">Document</a></li><li class="pure-menu-item sub-item"><a href="/docs/api.html#Model" class="pure-menu-link">Model</a></li><li class="pure-menu-item sub-item"><a href="/docs/api.html#Query" class="pure-menu-link">Query</a></li><li class="pure-menu-item sub-item"><a href="/docs/api.html#Aggregate" class="pure-menu-link">Aggregate</a></li><li class="pure-menu-item sub-item"><a href="/docs/api.html#Schematype" class="pure-menu-link">SchemaType</a></li><li class="pure-menu-item sub-item"><a href="/docs/api.html#Virtualtype" class="pure-menu-link">VirtualType</a></li><li class="pure-menu-item"><a href="/docs/compatibility.html" class="pure-menu-link">Version Compatibility</a></li><li class="pure-menu-item"><a href="/docs/faq.html" class="pure-menu-link">FAQ</a></li><li class="carbon-ad"><script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=mongoosejscom" id="_carbonads_js"></script></li></ul></div></div><div class="container"><div id="content"><h2 id="validation"><a href="#validation"><p>Validation</p>
</a></h2><p><p>Before we get into the specifics of validation syntax, please keep the following rules in mind:</p>
<ul>
<li>Validation is defined in the <a href="./schematypes.html">SchemaType</a></li>
<li>Validation is <a href="./middleware.html">middleware</a>. Mongoose registers validation as a <code>pre('save')</code> hook on every schema by default.</li>
<li>You can manually run validation using <code>doc.validate(callback)</code> or <code>doc.validateSync()</code></li>
<li>Validators are not run on undefined values. The only exception is the <a href="./api.html#schematype_SchemaType-required"><code>required</code> validator</a>.</li>
<li>Validation is asynchronously recursive; when you call <a href="./api.html#model_Model-save">Model#save</a>, sub-document validation is executed as well. If an error occurs, your <a href="./api.html#model_Model-save">Model#save</a> callback receives it</li>
<li>Validation is customizable</li>
</ul>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> schema = <span class="hljs-keyword">new</span> Schema({
name: {
type: <span class="hljs-built_in">String</span>,
required: <span class="hljs-literal">true</span>
}
});
<span class="hljs-keyword">var</span> Cat = db.model(<span class="hljs-string">'Cat'</span>, schema);
<span class="hljs-comment">// This cat has no name :(</span>
<span class="hljs-keyword">var</span> cat = <span class="hljs-keyword">new</span> Cat();
cat.save(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
assert.equal(error.errors[<span class="hljs-string">'name'</span>].message,
<span class="hljs-string">'Path `name` is required.'</span>);
error = cat.validateSync();
assert.equal(error.errors[<span class="hljs-string">'name'</span>].message,
<span class="hljs-string">'Path `name` is required.'</span>);
});
</code></pre>
<h2 id="built-in-validators"><a href="#built-in-validators"><p>Built-in Validators</p>
</a></h2><p><p>Mongoose has several built-in validators.</p>
<ul>
<li>All <a href="./schematypes.html">SchemaTypes</a> have the built-in <a href="./api.html#schematype_SchemaType-required">required</a> validator. The required validator uses the <a href="./api.html#schematype_SchemaType-checkRequired">SchemaType's <code>checkRequired()</code> function</a> to determine if the value satisfies the required validator.</li>
<li><a href="./api.html#schema-number-js">Numbers</a> have <a href="./api.html#schema_number_SchemaNumber-min">min</a> and <a href="./api.html#schema_number_SchemaNumber-max">max</a> validators.</li>
<li><a href="./api.html#schema-string-js">Strings</a> have <a href="./api.html#schema_string_SchemaString-enum">enum</a>, <a href="./api.html#schema_string_SchemaString-match">match</a>, <a href="./api.html#schema_string_SchemaString-maxlength">maxlength</a> and <a href="./api.html#schema_string_SchemaString-minlength">minlength</a> validators.</li>
</ul>
<p>Each of the validator links above provide more information about how to enable them and customize their error messages.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> breakfastSchema = <span class="hljs-keyword">new</span> Schema({
eggs: {
type: <span class="hljs-built_in">Number</span>,
min: [<span class="hljs-number">6</span>, <span class="hljs-string">'Too few eggs'</span>],
max: <span class="hljs-number">12</span>
},
bacon: {
type: <span class="hljs-built_in">Number</span>,
required: [<span class="hljs-literal">true</span>, <span class="hljs-string">'Why no bacon?'</span>]
},
drink: {
type: <span class="hljs-built_in">String</span>,
enum: [<span class="hljs-string">'Coffee'</span>, <span class="hljs-string">'Tea'</span>],
required: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.bacon > <span class="hljs-number">3</span>;
}
}
});
<span class="hljs-keyword">var</span> Breakfast = db.model(<span class="hljs-string">'Breakfast'</span>, breakfastSchema);
<span class="hljs-keyword">var</span> badBreakfast = <span class="hljs-keyword">new</span> Breakfast({
eggs: <span class="hljs-number">2</span>,
bacon: <span class="hljs-number">0</span>,
drink: <span class="hljs-string">'Milk'</span>
});
<span class="hljs-keyword">var</span> error = badBreakfast.validateSync();
assert.equal(error.errors[<span class="hljs-string">'eggs'</span>].message,
<span class="hljs-string">'Too few eggs'</span>);
assert.ok(!error.errors[<span class="hljs-string">'bacon'</span>]);
assert.equal(error.errors[<span class="hljs-string">'drink'</span>].message,
<span class="hljs-string">'`Milk` is not a valid enum value for path `drink`.'</span>);
badBreakfast.bacon = <span class="hljs-number">5</span>;
badBreakfast.drink = <span class="hljs-literal">null</span>;
error = badBreakfast.validateSync();
assert.equal(error.errors[<span class="hljs-string">'drink'</span>].message, <span class="hljs-string">'Path `drink` is required.'</span>);
badBreakfast.bacon = <span class="hljs-literal">null</span>;
error = badBreakfast.validateSync();
assert.equal(error.errors[<span class="hljs-string">'bacon'</span>].message, <span class="hljs-string">'Why no bacon?'</span>);
</code></pre>
<h2 id="the-unique-option-is-not-a-validator"><a href="#the-unique-option-is-not-a-validator"><p>The <code>unique</code> Option is Not a Validator</p>
</a></h2><p><p>A common gotcha for beginners is that the <code>unique</code> option for schemas
is <em>not</em> a validator. It's a convenient helper for building <a href="https://docs.mongodb.com/manual/core/index-unique/">MongoDB unique indexes</a>.
See the <a href="/docs/faq.html">FAQ</a> for more information.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> uniqueUsernameSchema = <span class="hljs-keyword">new</span> Schema({
username: {
type: <span class="hljs-built_in">String</span>,
unique: <span class="hljs-literal">true</span>
}
});
<span class="hljs-keyword">var</span> U1 = db.model(<span class="hljs-string">'U1'</span>, uniqueUsernameSchema);
<span class="hljs-keyword">var</span> U2 = db.model(<span class="hljs-string">'U2'</span>, uniqueUsernameSchema);
<span class="hljs-keyword">var</span> dup = [{ username: <span class="hljs-string">'Val'</span> }, { username: <span class="hljs-string">'Val'</span> }];
U1.create(dup, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
<span class="hljs-comment">// Race condition! This may save successfully, depending on whether</span>
<span class="hljs-comment">// MongoDB built the index before writing the 2 docs.</span>
});
<span class="hljs-comment">// Need to wait for the index to finish building before saving,</span>
<span class="hljs-comment">// otherwise unique constraints may be violated.</span>
U2.once(<span class="hljs-string">'index'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
assert.ifError(error);
U2.create(dup, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
<span class="hljs-comment">// Will error, but will *not* be a mongoose validation error, it will be</span>
<span class="hljs-comment">// a duplicate key error.</span>
assert.ok(error);
assert.ok(!error.errors);
assert.ok(error.message.indexOf(<span class="hljs-string">'duplicate key error'</span>) !== <span class="hljs-number">-1</span>);
});
});
<span class="hljs-comment">// There's also a promise-based equivalent to the event emitter API.</span>
<span class="hljs-comment">// The `init()` function is idempotent and returns a promise that</span>
<span class="hljs-comment">// will resolve once indexes are done building;</span>
U2.init().then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
U2.create(dup, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
<span class="hljs-comment">// Will error, but will *not* be a mongoose validation error, it will be</span>
<span class="hljs-comment">// a duplicate key error.</span>
assert.ok(error);
assert.ok(!error.errors);
assert.ok(error.message.indexOf(<span class="hljs-string">'duplicate key error'</span>) !== <span class="hljs-number">-1</span>);
});
});
</code></pre>
<h2 id="custom-validators"><a href="#custom-validators"><p>Custom Validators</p>
</a></h2><p><p>If the built-in validators aren't enough, you can define custom validators
to suit your needs.</p>
<p>Custom validation is declared by passing a validation function.
You can find detailed instructions on how to do this in the
<a href="./api.html#schematype_SchemaType-validate"><code>SchemaType#validate()</code> API docs</a>.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> userSchema = <span class="hljs-keyword">new</span> Schema({
phone: {
type: <span class="hljs-built_in">String</span>,
validate: {
validator: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">v</span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-regexp">/\d{3}-\d{3}-\d{4}/</span>.test(v);
},
message: <span class="hljs-string">'{VALUE} is not a valid phone number!'</span>
},
required: [<span class="hljs-literal">true</span>, <span class="hljs-string">'User phone number required'</span>]
}
});
<span class="hljs-keyword">var</span> User = db.model(<span class="hljs-string">'user'</span>, userSchema);
<span class="hljs-keyword">var</span> user = <span class="hljs-keyword">new</span> User();
<span class="hljs-keyword">var</span> error;
user.phone = <span class="hljs-string">'555.0123'</span>;
error = user.validateSync();
assert.equal(error.errors[<span class="hljs-string">'phone'</span>].message,
<span class="hljs-string">'555.0123 is not a valid phone number!'</span>);
user.phone = <span class="hljs-string">''</span>;
error = user.validateSync();
assert.equal(error.errors[<span class="hljs-string">'phone'</span>].message,
<span class="hljs-string">'User phone number required'</span>);
user.phone = <span class="hljs-string">'201-555-0123'</span>;
<span class="hljs-comment">// Validation succeeds! Phone number is defined</span>
<span class="hljs-comment">// and fits `DDD-DDD-DDDD`</span>
error = user.validateSync();
assert.equal(error, <span class="hljs-literal">null</span>);
</code></pre>
<h2 id="async-custom-validators"><a href="#async-custom-validators"><p>Async Custom Validators</p>
</a></h2><p><p>Custom validators can also be asynchronous. If your validator function
returns a promise (like an <code>async</code> function), mongoose will wait for that
promise to settle. If you prefer callbacks, set the <code>isAsync</code> option,
and mongoose will pass a callback as the 2nd argument to your validator
function.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> userSchema = <span class="hljs-keyword">new</span> Schema({
name: {
type: <span class="hljs-built_in">String</span>,
<span class="hljs-comment">// You can also make a validator async by returning a promise. If you</span>
<span class="hljs-comment">// return a promise, do **not** specify the `isAsync` option.</span>
validate: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">v</span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
setTimeout(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
resolve(<span class="hljs-literal">false</span>);
}, <span class="hljs-number">5</span>);
});
}
},
phone: {
type: <span class="hljs-built_in">String</span>,
validate: {
isAsync: <span class="hljs-literal">true</span>,
validator: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">v, cb</span>) </span>{
setTimeout(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">var</span> phoneRegex = <span class="hljs-regexp">/\d{3}-\d{3}-\d{4}/</span>;
<span class="hljs-keyword">var</span> msg = v + <span class="hljs-string">' is not a valid phone number!'</span>;
<span class="hljs-comment">// First argument is a boolean, whether validator succeeded</span>
<span class="hljs-comment">// 2nd argument is an optional error message override</span>
cb(phoneRegex.test(v), msg);
}, <span class="hljs-number">5</span>);
},
<span class="hljs-comment">// Default error message, overridden by 2nd argument to `cb()` above</span>
message: <span class="hljs-string">'Default error message'</span>
},
required: [<span class="hljs-literal">true</span>, <span class="hljs-string">'User phone number required'</span>]
}
});
<span class="hljs-keyword">var</span> User = db.model(<span class="hljs-string">'User'</span>, userSchema);
<span class="hljs-keyword">var</span> user = <span class="hljs-keyword">new</span> User();
<span class="hljs-keyword">var</span> error;
user.phone = <span class="hljs-string">'555.0123'</span>;
user.name = <span class="hljs-string">'test'</span>;
user.validate(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
assert.ok(error);
assert.equal(error.errors[<span class="hljs-string">'phone'</span>].message,
<span class="hljs-string">'555.0123 is not a valid phone number!'</span>);
assert.equal(error.errors[<span class="hljs-string">'name'</span>].message,
<span class="hljs-string">'Validator failed for path `name` with value `test`'</span>);
});
</code></pre>
<h2 id="validation-errors"><a href="#validation-errors"><p>Validation Errors</p>
</a></h2><p><p>Errors returned after failed validation contain an <code>errors</code> object
whose values are <code>ValidatorError</code> objects. Each
<a href="./api.html#error-validation-js">ValidatorError</a> has <code>kind</code>, <code>path</code>,
<code>value</code>, and <code>message</code> properties.
A ValidatorError also may have a <code>reason</code> property. If an error was
thrown in the validator, this property will contain the error that was
thrown.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> toySchema = <span class="hljs-keyword">new</span> Schema({
color: <span class="hljs-built_in">String</span>,
name: <span class="hljs-built_in">String</span>
});
<span class="hljs-keyword">var</span> validator = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value</span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-regexp">/red|white|gold/i</span>.test(value);
};
toySchema.path(<span class="hljs-string">'color'</span>).validate(validator,
<span class="hljs-string">'Color `{VALUE}` not valid'</span>, <span class="hljs-string">'Invalid color'</span>);
toySchema.path(<span class="hljs-string">'name'</span>).validate(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">v</span>) </span>{
<span class="hljs-keyword">if</span> (v !== <span class="hljs-string">'Turbo Man'</span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Need to get a Turbo Man for Christmas'</span>);
}
<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
}, <span class="hljs-string">'Name `{VALUE}` is not valid'</span>);
<span class="hljs-keyword">var</span> Toy = db.model(<span class="hljs-string">'Toy'</span>, toySchema);
<span class="hljs-keyword">var</span> toy = <span class="hljs-keyword">new</span> Toy({ color: <span class="hljs-string">'Green'</span>, name: <span class="hljs-string">'Power Ranger'</span> });
toy.save(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
<span class="hljs-comment">// `err` is a ValidationError object</span>
<span class="hljs-comment">// `err.errors.color` is a ValidatorError object</span>
assert.equal(err.errors.color.message, <span class="hljs-string">'Color `Green` not valid'</span>);
assert.equal(err.errors.color.kind, <span class="hljs-string">'Invalid color'</span>);
assert.equal(err.errors.color.path, <span class="hljs-string">'color'</span>);
assert.equal(err.errors.color.value, <span class="hljs-string">'Green'</span>);
<span class="hljs-comment">// This is new in mongoose 5. If your validator throws an exception,</span>
<span class="hljs-comment">// mongoose will use that message. If your validator returns `false`,</span>
<span class="hljs-comment">// mongoose will use the 'Name `Power Ranger` is not valid' message.</span>
assert.equal(err.errors.name.message,
<span class="hljs-string">'Need to get a Turbo Man for Christmas'</span>);
assert.equal(err.errors.name.value, <span class="hljs-string">'Power Ranger'</span>);
<span class="hljs-comment">// If your validator threw an error, the `reason` property will contain</span>
<span class="hljs-comment">// the original error thrown, including the original stack trace.</span>
assert.equal(err.errors.name.reason.message,
<span class="hljs-string">'Need to get a Turbo Man for Christmas'</span>);
assert.equal(err.name, <span class="hljs-string">'ValidationError'</span>);
});
</code></pre>
<h2 id="required-validators-on-nested-objects"><a href="#required-validators-on-nested-objects"><p>Required Validators On Nested Objects</p>
</a></h2><p><p>Defining validators on nested objects in mongoose is tricky, because
nested objects are not fully fledged paths.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> personSchema = <span class="hljs-keyword">new</span> Schema({
name: {
first: <span class="hljs-built_in">String</span>,
last: <span class="hljs-built_in">String</span>
}
});
assert.throws(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// This throws an error, because 'name' isn't a full fledged path</span>
personSchema.path(<span class="hljs-string">'name'</span>).required(<span class="hljs-literal">true</span>);
}, <span class="hljs-regexp">/Cannot.*'required'/</span>);
<span class="hljs-comment">// To make a nested object required, use a single nested schema</span>
<span class="hljs-keyword">var</span> nameSchema = <span class="hljs-keyword">new</span> Schema({
first: <span class="hljs-built_in">String</span>,
last: <span class="hljs-built_in">String</span>
});
personSchema = <span class="hljs-keyword">new</span> Schema({
name: {
type: nameSchema,
required: <span class="hljs-literal">true</span>
}
});
<span class="hljs-keyword">var</span> Person = db.model(<span class="hljs-string">'Person'</span>, personSchema);
<span class="hljs-keyword">var</span> person = <span class="hljs-keyword">new</span> Person();
<span class="hljs-keyword">var</span> error = person.validateSync();
assert.ok(error.errors[<span class="hljs-string">'name'</span>]);
</code></pre>
<h2 id="update-validators"><a href="#update-validators"><p>Update Validators</p>
</a></h2><p><p>In the above examples, you learned about document validation. Mongoose also
supports validation for <code>update()</code> and <code>findOneAndUpdate()</code> operations.
Update validators are off by default - you need to specify
the <code>runValidators</code> option.</p>
<p>To turn on update validators, set the <code>runValidators</code> option for
<code>update()</code> or <code>findOneAndUpdate()</code>. Be careful: update validators
are off by default because they have several caveats.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> toySchema = <span class="hljs-keyword">new</span> Schema({
color: <span class="hljs-built_in">String</span>,
name: <span class="hljs-built_in">String</span>
});
<span class="hljs-keyword">var</span> Toy = db.model(<span class="hljs-string">'Toys'</span>, toySchema);
Toy.schema.path(<span class="hljs-string">'color'</span>).validate(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value</span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-regexp">/blue|green|white|red|orange|periwinkle/i</span>.test(value);
}, <span class="hljs-string">'Invalid color'</span>);
<span class="hljs-keyword">var</span> opts = { runValidators: <span class="hljs-literal">true</span> };
Toy.update({}, { color: <span class="hljs-string">'bacon'</span> }, opts, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
assert.equal(err.errors.color.message,
<span class="hljs-string">'Invalid color'</span>);
});
</code></pre>
<h2 id="update-validators-and-this"><a href="#update-validators-and-this"><p>Update Validators and <code>this</code></p>
</a></h2><p><p>There are a couple of key differences between update validators and
document validators. In the color validation function above, <code>this</code> refers
to the document being validated when using document validation.
However, when running update validators, the document being updated
may not be in the server's memory, so by default the value of <code>this</code> is
not defined.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> toySchema = <span class="hljs-keyword">new</span> Schema({
color: <span class="hljs-built_in">String</span>,
name: <span class="hljs-built_in">String</span>
});
toySchema.path(<span class="hljs-string">'color'</span>).validate(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value</span>) </span>{
<span class="hljs-comment">// When running in `validate()` or `validateSync()`, the</span>
<span class="hljs-comment">// validator can access the document using `this`.</span>
<span class="hljs-comment">// Does **not** work with update validators.</span>
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.name.toLowerCase().indexOf(<span class="hljs-string">'red'</span>) !== <span class="hljs-number">-1</span>) {
<span class="hljs-keyword">return</span> value !== <span class="hljs-string">'red'</span>;
}
<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
});
<span class="hljs-keyword">var</span> Toy = db.model(<span class="hljs-string">'ActionFigure'</span>, toySchema);
<span class="hljs-keyword">var</span> toy = <span class="hljs-keyword">new</span> Toy({ color: <span class="hljs-string">'red'</span>, name: <span class="hljs-string">'Red Power Ranger'</span> });
<span class="hljs-keyword">var</span> error = toy.validateSync();
assert.ok(error.errors[<span class="hljs-string">'color'</span>]);
<span class="hljs-keyword">var</span> update = { color: <span class="hljs-string">'red'</span>, name: <span class="hljs-string">'Red Power Ranger'</span> };
<span class="hljs-keyword">var</span> opts = { runValidators: <span class="hljs-literal">true</span> };
Toy.update({}, update, opts, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
<span class="hljs-comment">// The update validator throws an error:</span>
<span class="hljs-comment">// "TypeError: Cannot read property 'toLowerCase' of undefined",</span>
<span class="hljs-comment">// because `this` is **not** the document being updated when using</span>
<span class="hljs-comment">// update validators</span>
assert.ok(error);
});
</code></pre>
<h2 id="the-context-option"><a href="#the-context-option"><p>The <code>context</code> option</p>
</a></h2><p><p>The <code>context</code> option lets you set the value of <code>this</code> in update validators
to the underlying query.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-comment">// acquit:ignore:start</span>
<span class="hljs-keyword">var</span> toySchema = <span class="hljs-keyword">new</span> Schema({
color: <span class="hljs-built_in">String</span>,
name: <span class="hljs-built_in">String</span>
});
<span class="hljs-comment">// acquit:ignore:end</span>
toySchema.path(<span class="hljs-string">'color'</span>).validate(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value</span>) </span>{
<span class="hljs-comment">// When running update validators with the `context` option set to</span>
<span class="hljs-comment">// 'query', `this` refers to the query object.</span>
<span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.getUpdate().$set.name.toLowerCase().indexOf(<span class="hljs-string">'red'</span>) !== <span class="hljs-number">-1</span>) {
<span class="hljs-keyword">return</span> value === <span class="hljs-string">'red'</span>;
}
<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
});
<span class="hljs-keyword">var</span> Toy = db.model(<span class="hljs-string">'Figure'</span>, toySchema);
<span class="hljs-keyword">var</span> update = { color: <span class="hljs-string">'blue'</span>, name: <span class="hljs-string">'Red Power Ranger'</span> };
<span class="hljs-comment">// Note the context option</span>
<span class="hljs-keyword">var</span> opts = { runValidators: <span class="hljs-literal">true</span>, context: <span class="hljs-string">'query'</span> };
Toy.update({}, update, opts, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
assert.ok(error.errors[<span class="hljs-string">'color'</span>]);
});
</code></pre>
<h2 id="update-validators-only-run-on-updated-paths"><a href="#update-validators-only-run-on-updated-paths"><p>Update Validators Only Run On Updated Paths</p>
</a></h2><p><p>The other key difference that update validators only run on the paths
specified in the update. For instance, in the below example, because
'name' is not specified in the update operation, update validation will
succeed.</p>
<p>When using update validators, <code>required</code> validators <strong>only</strong> fail when
you try to explicitly <code>$unset</code> the key.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-comment">// acquit:ignore:start</span>
<span class="hljs-keyword">var</span> outstanding = <span class="hljs-number">2</span>;
<span class="hljs-comment">// acquit:ignore:end</span>
<span class="hljs-keyword">var</span> kittenSchema = <span class="hljs-keyword">new</span> Schema({
name: { type: <span class="hljs-built_in">String</span>, required: <span class="hljs-literal">true</span> },
age: <span class="hljs-built_in">Number</span>
});
<span class="hljs-keyword">var</span> Kitten = db.model(<span class="hljs-string">'Kitten'</span>, kittenSchema);
<span class="hljs-keyword">var</span> update = { color: <span class="hljs-string">'blue'</span> };
<span class="hljs-keyword">var</span> opts = { runValidators: <span class="hljs-literal">true</span> };
Kitten.update({}, update, opts, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>) </span>{
<span class="hljs-comment">// Operation succeeds despite the fact that 'name' is not specified</span>
});
<span class="hljs-keyword">var</span> unset = { $unset: { name: <span class="hljs-number">1</span> } };
Kitten.update({}, unset, opts, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>) </span>{
<span class="hljs-comment">// Operation fails because 'name' is required</span>
assert.ok(err);
assert.ok(err.errors[<span class="hljs-string">'name'</span>]);
});
</code></pre>
<h2 id="update-validators-only-run-for-some-operations"><a href="#update-validators-only-run-for-some-operations"><p>Update Validators Only Run For Some Operations</p>
</a></h2><p><p>One final detail worth noting: update validators <strong>only</strong> run on the
following update operators:</p>
<ul>
<li><code>$set</code></li>
<li><code>$unset</code></li>
<li><code>$push</code> (>= 4.8.0)</li>
<li><code>$addToSet</code> (>= 4.8.0)</li>
<li><code>$pull</code> (>= 4.12.0)</li>
<li><code>$pullAll</code> (>= 4.12.0)</li>
</ul>
<p>For instance, the below update will succeed, regardless of the value of
<code>number</code>, because update validators ignore <code>$inc</code>.</p>
<p>Also, <code>$push</code>, <code>$addToSet</code>, <code>$pull</code>, and <code>$pullAll</code> validation does
<strong>not</strong> run any validation on the array itself, only individual elements
of the array.</p>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> testSchema = <span class="hljs-keyword">new</span> Schema({
number: { type: <span class="hljs-built_in">Number</span>, max: <span class="hljs-number">0</span> },
arr: [{ message: { type: <span class="hljs-built_in">String</span>, maxlength: <span class="hljs-number">10</span> } }]
});
<span class="hljs-comment">// Update validators won't check this, so you can still `$push` 2 elements</span>
<span class="hljs-comment">// onto the array, so long as they don't have a `message` that's too long.</span>
testSchema.path(<span class="hljs-string">'arr'</span>).validate(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">v</span>) </span>{
<span class="hljs-keyword">return</span> v.length < <span class="hljs-number">2</span>;
});
<span class="hljs-keyword">var</span> Test = db.model(<span class="hljs-string">'Test'</span>, testSchema);
<span class="hljs-keyword">var</span> update = { $inc: { number: <span class="hljs-number">1</span> } };
<span class="hljs-keyword">var</span> opts = { runValidators: <span class="hljs-literal">true</span> };
Test.update({}, update, opts, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
<span class="hljs-comment">// There will never be a validation error here</span>
update = { $push: [{ message: <span class="hljs-string">'hello'</span> }, { message: <span class="hljs-string">'world'</span> }] };
Test.update({}, update, opts, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
<span class="hljs-comment">// This will never error either even though the array will have at</span>
<span class="hljs-comment">// least 2 elements.</span>
});
});
</code></pre>
<h2 id="on-$push-and-$addtoset"><a href="#on-$push-and-$addtoset"><p>On $push and $addToSet</p>
</a></h2><p><p>New in 4.8.0: update validators also run on <code>$push</code> and <code>$addToSet</code></p>
</p>
<pre><code class="lang-javscript"><span class="hljs-keyword">var</span> testSchema = <span class="hljs-keyword">new</span> Schema({
numbers: [{ type: <span class="hljs-built_in">Number</span>, max: <span class="hljs-number">0</span> }],
docs: [{
name: { type: <span class="hljs-built_in">String</span>, required: <span class="hljs-literal">true</span> }
}]
});
<span class="hljs-keyword">var</span> Test = db.model(<span class="hljs-string">'TestPush'</span>, testSchema);
<span class="hljs-keyword">var</span> update = {
$push: {
numbers: <span class="hljs-number">1</span>,
docs: { name: <span class="hljs-literal">null</span> }
}
};
<span class="hljs-keyword">var</span> opts = { runValidators: <span class="hljs-literal">true</span> };
Test.update({}, update, opts, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error</span>) </span>{
assert.ok(error.errors[<span class="hljs-string">'numbers'</span>]);
assert.ok(error.errors[<span class="hljs-string">'docs'</span>]);
});
</code></pre>
</div></div><script type="text/javascript">!function(name,path,ctx){
var latest,prev=name!=='Keen'&&window.Keen?window.Keen:false;ctx[name]=ctx[name]||{ready:function(fn){var h=document.getElementsByTagName('head')[0],s=document.createElement('script'),w=window,loaded;s.onload=s.onerror=s.onreadystatechange=function(){if((s.readyState&&!(/^c|loade/.test(s.readyState)))||loaded){return}s.onload=s.onreadystatechange=null;loaded=1;latest=w.Keen;if(prev){w.Keen=prev}else{try{delete w.Keen}catch(e){w.Keen=void 0}}ctx[name]=latest;ctx[name].ready(fn)};s.async=1;s.src=path;h.parentNode.insertBefore(s,h)}}
}('KeenAsync','https://d26b395fwzu5fz.cloudfront.net/keen-tracking-1.1.3.min.js',this);
KeenAsync.ready(function(){
// Configure a client instance
var client = new KeenAsync({
projectId: '59aad9cbc9e77c0001ce1b32',
writeKey: '4B38B0046086885E425D368BFAEAD8FD0D4F2DC2FA2F936FDE058D79508AEFAD9886BC020B96520823BB9C8241D9D9BCFDC0EF52E6033BD89D06E4B24FC13AE955896BF443406269A84DD009CEB5862DCEC944874DB2107FD648DA91ADC1E6DE'
});
client.recordEvent('pageView', {
host: window.location.host,
pathname: window.location.pathname,
hash: window.location.hash
});
});</script><script type="text/javascript">(function (window, document) {
var layout = document.getElementById('layout'),
menu = document.getElementById('menu'),
menuLink = document.getElementById('menuLink'),
content = document.getElementById('content');
function toggleClass(element, className) {
var classes = element.className.split(/\s+/),
length = classes.length,
i = 0;
for(; i < length; i++) {
if (classes[i] === className) {
classes.splice(i, 1);
break;
}
}
// The className is not found
if (length === classes.length) {
classes.push(className);
}
element.className = classes.join(' ');
}
function toggleAll(e) {
var active = 'active';
e.preventDefault();
toggleClass(layout, active);
toggleClass(menu, active);
toggleClass(menuLink, active);
}
menuLink.onclick = function (e) {
toggleAll(e);
};
content.onclick = function(e) {
if (menu.className.indexOf('active') !== -1) {
toggleAll(e);
}
};
}(this, this.document));</script></div></body></html>