forked from Automattic/mongoose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocument.js
1710 lines (1464 loc) · 42 KB
/
document.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
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter
, setMaxListeners = EventEmitter.prototype.setMaxListeners
, MongooseError = require('./error')
, MixedSchema = require('./schema/mixed')
, Schema = require('./schema')
, ValidatorError = require('./schematype').ValidatorError
, utils = require('./utils')
, clone = utils.clone
, isMongooseObject = utils.isMongooseObject
, inspect = require('util').inspect
, ElemMatchError = MongooseError.ElemMatchError
, ValidationError = MongooseError.ValidationError
, DocumentError = MongooseError.DocumentError
, InternalCache = require('./internal')
, deepEqual = utils.deepEqual
, hooks = require('hooks')
, DocumentArray
, MongooseArray
, Embedded
/**
* Document constructor.
*
* @param {Object} obj the values to set
* @param {Object} [opts] optional object containing the fields which were selected in the query returning this document and any populated paths data
* @param {Boolean} [skipId] bool, should we auto create an ObjectId _id
* @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter
* @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose.
* @event `save`: Emitted when the document is successfully saved
* @api private
*/
function Document (obj, fields, skipId) {
this.$__ = new InternalCache;
this.isNew = true;
this.errors = undefined;
var schema = this.schema;
if ('boolean' === typeof fields) {
this.$__.strictMode = fields;
fields = undefined;
} else {
this.$__.strictMode = schema.options && schema.options.strict;
this.$__.selected = fields;
}
var required = schema.requiredPaths();
for (var i = 0; i < required.length; ++i) {
this.$__.activePaths.require(required[i]);
}
setMaxListeners.call(this, 0);
this._doc = this.$__buildDoc(obj, fields, skipId);
if (obj) {
this.set(obj, undefined, true);
}
this.$__registerHooks();
}
/*!
* Inherit from EventEmitter.
*/
Document.prototype.__proto__ = EventEmitter.prototype;
/**
* The documents schema.
*
* @api public
* @property schema
*/
Document.prototype.schema;
/**
* Boolean flag specifying if the document is new.
*
* @api public
* @property isNew
*/
Document.prototype.isNew;
/**
* The string version of this documents _id.
*
* ####Note:
*
* This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time.
*
* new Schema({ name: String }, { id: false });
*
* @api public
* @see Schema options /docs/guide.html#options
* @property id
*/
Document.prototype.id;
/**
* Hash containing current validation errors.
*
* @api public
* @property errors
*/
Document.prototype.errors;
/**
* Builds the default doc structure
*
* @param {Object} obj
* @param {Object} [fields]
* @param {Boolean} [skipId]
* @return {Object}
* @api private
* @method $__buildDoc
* @memberOf Document
*/
Document.prototype.$__buildDoc = function (obj, fields, skipId) {
var doc = {}
, self = this
, exclude
, keys
, key
, ki
// determine if this doc is a result of a query with
// excluded fields
if (fields && 'Object' === fields.constructor.name) {
keys = Object.keys(fields);
ki = keys.length;
while (ki--) {
if ('_id' !== keys[ki]) {
exclude = 0 === fields[keys[ki]];
break;
}
}
}
var paths = Object.keys(this.schema.paths)
, plen = paths.length
, ii = 0
for (; ii < plen; ++ii) {
var p = paths[ii];
if ('_id' == p) {
if (skipId) continue;
if (obj && '_id' in obj) continue;
}
var type = this.schema.paths[p]
, path = p.split('.')
, len = path.length
, last = len-1
, doc_ = doc
, i = 0
for (; i < len; ++i) {
var piece = path[i]
, def
if (i === last) {
if (fields) {
if (exclude) {
// apply defaults to all non-excluded fields
if (p in fields) continue;
def = type.getDefault(self, true);
if ('undefined' !== typeof def) {
doc_[piece] = def;
self.$__.activePaths.default(p);
}
} else if (p in fields) {
// selected field
def = type.getDefault(self, true);
if ('undefined' !== typeof def) {
doc_[piece] = def;
self.$__.activePaths.default(p);
}
}
} else {
def = type.getDefault(self, true);
if ('undefined' !== typeof def) {
doc_[piece] = def;
self.$__.activePaths.default(p);
}
}
} else {
doc_ = doc_[piece] || (doc_[piece] = {});
}
}
};
return doc;
};
/**
* Initializes the document without setters or marking anything modified.
*
* Called internally after a document is returned from mongodb.
*
* @param {Object} doc document returned by mongo
* @param {Function} fn callback
* @api private
*/
Document.prototype.init = function (doc, opts, fn) {
// do not prefix this method with $__ since its
// used by public hooks
if ('function' == typeof opts) {
fn = opts;
opts = null;
}
this.isNew = false;
// handle docs with populated paths
if (doc._id && opts && opts.populated && opts.populated.length) {
var id = String(doc._id);
for (var i = 0; i < opts.populated.length; ++i) {
var item = opts.populated[i];
this.populated(item.path, item._docs[id], item);
}
}
init(this, doc, this._doc);
this.$__storeShard();
this.emit('init', this);
if (fn) fn(null);
return this;
};
/*!
* Init helper.
*
* @param {Object} self document instance
* @param {Object} obj raw mongodb doc
* @param {Object} doc object we are initializing
* @api private
*/
function init (self, obj, doc, prefix) {
prefix = prefix || '';
var keys = Object.keys(obj)
, len = keys.length
, schema
, path
, i;
while (len--) {
i = keys[len];
path = prefix + i;
schema = self.schema.path(path);
if (!schema && obj[i] && 'Object' === obj[i].constructor.name) {
// assume nested object
if (!doc[i]) doc[i] = {};
init(self, obj[i], doc[i], path + '.');
} else {
if (obj[i] === null) {
doc[i] = null;
} else if (obj[i] !== undefined) {
if (schema) {
self.$__try(function(){
doc[i] = schema.cast(obj[i], self, true);
});
} else {
doc[i] = obj[i];
}
}
// mark as hydrated
self.$__.activePaths.init(path);
}
}
};
/**
* Stores the current values of the shard keys.
*
* ####Note:
*
* _Shard key values do not / are not allowed to change._
*
* @api private
* @method $__storeShard
* @memberOf Document
*/
Document.prototype.$__storeShard = function () {
// backwards compat
var key = this.schema.options.shardKey || this.schema.options.shardkey;
if (!(key && 'Object' == key.constructor.name)) return;
var orig = this.$__.shardval = {}
, paths = Object.keys(key)
, len = paths.length
, val
for (var i = 0; i < len; ++i) {
val = this.getValue(paths[i]);
if (isMongooseObject(val)) {
orig[paths[i]] = val.toObject({ depopulate: true })
} else if (null != val && val.valueOf) {
orig[paths[i]] = val.valueOf();
} else {
orig[paths[i]] = val;
}
}
}
/*!
* Set up middleware support
*/
for (var k in hooks) {
Document.prototype[k] = Document[k] = hooks[k];
}
/**
* Sends an update command with this document `_id` as the query selector.
*
* ####Example:
*
* weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);
*
* ####Valid options:
*
* - same as in [Model.update](#model_Model.update)
*
* @see Model.update #model_Model.update
* @param {Object} doc
* @param {Object} options
* @param {Function} callback
* @return {Query}
* @api public
*/
Document.prototype.update = function update () {
var args = utils.args(arguments);
args.unshift({_id: this._id});
return this.constructor.update.apply(this.constructor, args);
}
/**
* Sets the value of a path, or many paths.
*
* ####Example:
*
* // path, value
* doc.set(path, value)
*
* // object
* doc.set({
* path : value
* , path2 : {
* path : value
* }
* })
*
* // only-the-fly cast to number
* doc.set(path, value, Number)
*
* // only-the-fly cast to string
* doc.set(path, value, String)
*
* // changing strict mode behavior
* doc.set(path, value, { strict: false });
*
* @param {String|Object} path path or object of key/vals to set
* @param {Any} val the value to set
* @param {Schema|String|Number|Buffer|etc..} [type] optionally specify a type for "on-the-fly" attributes
* @param {Object} [options] optionally specify options that modify the behavior of the set
* @api public
*/
Document.prototype.set = function (path, val, type, options) {
if (type && 'Object' == type.constructor.name) {
options = type;
type = undefined;
}
var merge = options && options.merge
, adhoc = type && true !== type
, constructing = true === type
, adhocs
var strict = options && 'strict' in options
? options.strict
: this.$__.strictMode;
if (adhoc) {
adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
adhocs[path] = Schema.interpretAsType(path, type);
}
if ('string' !== typeof path) {
// new Document({ key: val })
if (null === path || undefined === path) {
var _ = path;
path = val;
val = _;
} else {
var prefix = val
? val + '.'
: '';
if (path instanceof Document) path = path._doc;
var keys = Object.keys(path)
, i = keys.length
, pathtype
, key
while (i--) {
key = keys[i];
pathtype = this.schema.pathType(prefix + key);
if (null != path[key]
&& 'Object' == path[key].constructor.name
&& 'virtual' != pathtype
&& !(this.$__path(prefix + key) instanceof MixedSchema)) {
this.set(path[key], prefix + key, constructing);
} else if (strict) {
if ('real' === pathtype || 'virtual' === pathtype) {
this.set(prefix + key, path[key], constructing);
} else if ('throw' == strict) {
throw new Error("Field `" + key + "` is not in schema.");
}
} else if (undefined !== path[key]) {
this.set(prefix + key, path[key], constructing);
}
}
return this;
}
}
// ensure _strict is honored for obj props
// docschema = new Schema({ path: { nest: 'string' }})
// doc.set('path', obj);
var pathType = this.schema.pathType(path);
if ('nested' == pathType && val && 'Object' == val.constructor.name) {
if (!merge) this.setValue(path, null);
this.set(val, path, constructing);
return this;
}
var schema;
var parts = path.split('.');
if ('adhocOrUndefined' == pathType && strict) {
// check for roots that are Mixed types
var mixed;
for (var i = 0; i < parts.length; ++i) {
var subpath = parts.slice(0, i+1).join('.');
schema = this.schema.path(subpath);
if (schema instanceof MixedSchema) {
// allow changes to sub paths of mixed types
mixed = true;
break;
}
}
if (!mixed) {
if ('throw' == strict) {
throw new Error("Field `" + path + "` is not in schema.");
}
return this;
}
} else if ('virtual' == pathType) {
schema = this.schema.virtualpath(path);
schema.applySetters(val, this);
return this;
} else {
schema = this.$__path(path);
}
var pathToMark;
// When using the $set operator the path to the field must already exist.
// Else mongodb throws: "LEFT_SUBFIELD only supports Object"
if (parts.length <= 1) {
pathToMark = path;
} else {
for (var i = 0; i < parts.length; ++i) {
var subpath = parts.slice(0, i+1).join('.');
if (this.isDirectModified(subpath) // earlier prefixes that are already
// marked as dirty have precedence
|| this.get(subpath) === null) {
pathToMark = subpath;
break;
}
}
if (!pathToMark) pathToMark = path;
}
// if this doc is being constructed we should not trigger getters
var priorVal = constructing
? undefined
: this.get(path);
if (!schema || null === val || undefined === val) {
this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
return this;
}
var self = this;
var shouldSet = this.$__try(function(){
val = schema.applySetters(val, self, false, priorVal);
});
if (shouldSet) {
this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal);
}
return this;
}
/**
* Determine if we should mark this change as modified.
*
* @return {Boolean}
* @api private
* @method $__shouldModify
* @memberOf Document
*/
Document.prototype.$__shouldModify = function (
pathToMark, path, constructing, parts, schema, val, priorVal) {
if (this.isNew) return true;
if (this.isDirectModified(pathToMark)) return false;
if (undefined === val && !this.isSelected(path)) {
// when a path is not selected in a query, its initial
// value will be undefined.
return true;
}
if (undefined === val && path in this.$__.activePaths.states.default) {
// we're just unsetting the default value which was never saved
return false;
}
if (!deepEqual(val, priorVal || this.get(path))) {
return true;
}
if (!constructing &&
null != val &&
path in this.$__.activePaths.states.default &&
deepEqual(val, schema.getDefault(this, constructing))) {
// a path with a default was $unset on the server
// and the user is setting it to the same value again
return true;
}
return false;
}
/**
* Handles the actual setting of the value and marking the path modified if appropriate.
*
* @api private
* @method $__set
* @memberOf Document
*/
Document.prototype.$__set = function (
pathToMark, path, constructing, parts, schema, val, priorVal) {
var shouldModify = this.$__shouldModify.apply(this, arguments);
if (shouldModify) {
this.markModified(pathToMark, val);
// handle directly setting arrays (gh-1126)
MongooseArray || (MongooseArray = require('./types/array'));
if (val instanceof MongooseArray) {
val._registerAtomic('$set', val);
}
}
var obj = this._doc
, i = 0
, l = parts.length
for (; i < l; i++) {
var next = i + 1
, last = next === l;
if (last) {
obj[parts[i]] = val;
} else {
if (obj[parts[i]] && 'Object' === obj[parts[i]].constructor.name) {
obj = obj[parts[i]];
} else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) {
obj = obj[parts[i]];
} else {
obj = obj[parts[i]] = {};
}
}
}
}
/**
* Gets a raw value from a path (no getters)
*
* @param {String} path
* @api private
*/
Document.prototype.getValue = function (path) {
return utils.getValue(path, this._doc);
}
/**
* Sets a raw value for a path (no casting, setters, transformations)
*
* @param {String} path
* @param {Object} value
* @api private
*/
Document.prototype.setValue = function (path, val) {
utils.setValue(path, val, this._doc);
return this;
}
/**
* Returns the value of a path.
*
* ####Example
*
* // path
* doc.get('age') // 47
*
* // dynamic casting to a string
* doc.get('age', String) // "47"
*
* @param {String} path
* @param {Schema|String|Number|Buffer|etc..} [type] optionally specify a type for on-the-fly attributes
* @api public
*/
Document.prototype.get = function (path, type) {
var adhocs;
if (type) {
adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {});
adhocs[path] = Schema.interpretAsType(path, type);
}
var schema = this.$__path(path) || this.schema.virtualpath(path)
, pieces = path.split('.')
, obj = this._doc;
for (var i = 0, l = pieces.length; i < l; i++) {
obj = undefined === obj || null === obj
? undefined
: obj[pieces[i]];
}
if (schema) {
obj = schema.applyGetters(obj, this);
}
return obj;
};
/**
* Returns the schematype for the given `path`.
*
* @param {String} path
* @api private
* @method $__path
* @memberOf Document
*/
Document.prototype.$__path = function (path) {
var adhocs = this.$__.adhocPaths
, adhocType = adhocs && adhocs[path];
if (adhocType) {
return adhocType;
} else {
return this.schema.path(path);
}
};
/**
* Marks the path as having pending changes to write to the db.
*
* _Very helpful when using [Mixed](./schematypes.html#mixed) types._
*
* ####Example:
*
* doc.mixed.type = 'changed';
* doc.markModified('mixed.type');
* doc.save() // changes to mixed.type are now persisted
*
* @param {String} path the path to mark modified
* @api public
*/
Document.prototype.markModified = function (path) {
this.$__.activePaths.modify(path);
}
/**
* Catches errors that occur during execution of `fn` and stores them to later be passed when `save()` is executed.
*
* @param {Function} fn function to execute
* @param {Object} scope the scope with which to call fn
* @api private
* @method $__try
* @memberOf Document
*/
Document.prototype.$__try = function (fn, scope) {
var res;
try {
fn.call(scope);
res = true;
} catch (e) {
this.$__error(e);
res = false;
}
return res;
};
/**
* Returns the list of paths that have been modified.
*
* @return {Array}
* @api public
*/
Document.prototype.modifiedPaths = function () {
var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
return directModifiedPaths.reduce(function (list, path) {
var parts = path.split('.');
return list.concat(parts.reduce(function (chains, part, i) {
return chains.concat(parts.slice(0, i).concat(part).join('.'));
}, []));
}, []);
};
/**
* Returns true if this document was modified, else false.
*
* If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified.
*
* ####Example
*
* doc.set('documents.0.title', 'changed');
* doc.isModified() // true
* doc.isModified('documents') // true
* doc.isModified('documents.0.title') // true
* doc.isDirectModified('documents') // false
*
* @param {String} [path] optional
* @return {Boolean}
* @api public
*/
Document.prototype.isModified = function (path) {
return path
? !!~this.modifiedPaths().indexOf(path)
: this.$__.activePaths.some('modify');
};
/**
* Returns true if `path` was directly set and modified, else false.
*
* ####Example
*
* doc.set('documents.0.title', 'changed');
* doc.isDirectModified('documents.0.title') // true
* doc.isDirectModified('documents') // false
*
* @param {String} path
* @return {Boolean}
* @api public
*/
Document.prototype.isDirectModified = function (path) {
return (path in this.$__.activePaths.states.modify);
};
/**
* Checks if `path` was initialized.
*
* @param {String} path
* @return {Boolean}
* @api public
*/
Document.prototype.isInit = function (path) {
return (path in this.$__.activePaths.states.init);
};
/**
* Checks if `path` was selected in the source query which initialized this document.
*
* ####Example
*
* Thing.findOne().select('name').exec(function (err, doc) {
* doc.isSelected('name') // true
* doc.isSelected('age') // false
* })
*
* @param {String} path
* @return {Boolean}
* @api public
*/
Document.prototype.isSelected = function isSelected (path) {
if (this.$__.selected) {
if ('_id' === path) {
return 0 !== this.$__.selected._id;
}
var paths = Object.keys(this.$__.selected)
, i = paths.length
, inclusive = false
, cur
if (1 === i && '_id' === paths[0]) {
// only _id was selected.
return 0 === this.$__.selected._id;
}
while (i--) {
cur = paths[i];
if ('_id' == cur) continue;
inclusive = !! this.$__.selected[cur];
break;
}
if (path in this.$__.selected) {
return inclusive;
}
i = paths.length;
var pathDot = path + '.';
while (i--) {
cur = paths[i];
if ('_id' == cur) continue;
if (0 === cur.indexOf(pathDot)) {
return inclusive;
}
if (0 === pathDot.indexOf(cur)) {
return inclusive;
}
}
return ! inclusive;
}
return true;
}
/**
* Executes registered validation rules for this document.
*
* ####Note:
*
* This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`.
*
* ####Example:
*
* doc.validate(function (err) {
* if (err) handleError(err);
* else // validation passed
* });
*
* @param {Function} cb called after validation completes, passing an error if one occurred
* @api public
*/
Document.prototype.validate = function (cb) {
var self = this
// only validate required fields when necessary
var paths = Object.keys(this.$__.activePaths.states.require).filter(function (path) {
if (!self.isSelected(path) && !self.isModified(path)) return false;
return true;
});
paths = paths.concat(Object.keys(this.$__.activePaths.states.init));
paths = paths.concat(Object.keys(this.$__.activePaths.states.modify));
paths = paths.concat(Object.keys(this.$__.activePaths.states.default));
if (0 === paths.length) {
complete();
return this;
}
var validating = {}
, total = 0;
paths.forEach(validatePath);
return this;
function validatePath (path) {
if (validating[path]) return;
validating[path] = true;
total++;
process.nextTick(function(){
var p = self.schema.path(path);
if (!p) return --total || complete();
var val = self.getValue(path);
p.doValidate(val, function (err) {
if (err) {
self.invalidate(
path
, err
, undefined
, true // embedded docs
);
}
--total || complete();
}, self);
});
}
function complete () {
var err = self.$__.validationError;
self.$__.validationError = undefined;
self.emit('validate', self);
cb(err);
}
};
/**
* Marks a path as invalid, causing validation to fail.
*
* @param {String} path the field to invalidate
* @param {String|Error} err the error which states the reason `path` was invalid
* @param {Object|String|Number|any} value optional invalid value
* @api public
*/
Document.prototype.invalidate = function (path, err, val) {
if (!this.$__.validationError) {
this.$__.validationError = new ValidationError(this);
}
if (!err || 'string' === typeof err) {
// sniffing arguments:
// need to handle case where user does not pass value
// so our error message is cleaner
err = 2 < arguments.length
? new ValidatorError(path, err, val)
: new ValidatorError(path, err)
}
this.$__.validationError.errors[path] = err;
}
/**
* Resets the internal modified state of this document.
*
* @api private
* @return {Document}
* @method $__reset
* @memberOf Document
*/
Document.prototype.$__reset = function reset () {
var self = this;