-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathmodel.test.js
7368 lines (5938 loc) · 214 KB
/
model.test.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
'use strict';
/**
* Test dependencies.
*/
const sinon = require('sinon');
const start = require('./common');
const assert = require('assert');
const random = require('./util').random;
const util = require('./util');
const mongoose = start.mongoose;
const Schema = mongoose.Schema;
const ValidatorError = mongoose.Error.ValidatorError;
const ValidationError = mongoose.Error.ValidationError;
const ObjectId = Schema.Types.ObjectId;
const DocumentObjectId = mongoose.Types.ObjectId;
const EmbeddedDocument = mongoose.Types.Subdocument;
const MongooseError = mongoose.Error;
describe('Model', function() {
let db;
let Comments;
let BlogPost;
beforeEach(() => db.deleteModel(/.*/));
beforeEach(function() {
Comments = new Schema();
Comments.add({
title: String,
date: Date,
body: String,
comments: [Comments]
});
BlogPost = new Schema({
title: String,
author: String,
slug: String,
date: Date,
meta: {
date: Date,
visitors: Number
},
published: Boolean,
mixed: {},
numbers: [Number],
owners: [ObjectId],
comments: [Comments],
nested: { array: [Number] }
});
BlogPost
.virtual('titleWithAuthor')
.get(function() {
return this.get('title') + ' by ' + this.get('author');
})
.set(function(val) {
const split = val.split(' by ');
this.set('title', split[0]);
this.set('author', split[1]);
});
BlogPost.method('cool', function() {
return this;
});
BlogPost.static('woot', function() {
return this;
});
BlogPost = db.model('BlogPost', BlogPost);
});
before(function() {
db = start();
});
after(async function() {
await db.close();
});
afterEach(() => util.clearTestData(db));
afterEach(() => require('./util').stopRemainingOps(db));
it('can be created using _id as embedded document', async function() {
const Test = db.model('Test', Schema({
_id: { first_name: String, age: Number },
last_name: String,
doc_embed: {
some: String
}
}));
await Test.deleteMany();
const t = new Test({
_id: {
first_name: 'Daniel',
age: 21
},
last_name: 'Alabi',
doc_embed: {
some: 'a'
}
});
await t.save();
const doc = await Test.findOne();
assert.ok('last_name' in doc);
assert.ok('_id' in doc);
assert.ok('first_name' in doc._id);
assert.equal(doc._id.first_name, 'Daniel');
assert.ok('age' in doc._id);
assert.equal(doc._id.age, 21);
assert.ok('doc_embed' in doc);
assert.ok('some' in doc.doc_embed);
assert.equal(doc.doc_embed.some, 'a');
});
describe('constructor', function() {
it('works without "new" keyword', function() {
const B = BlogPost;
let b = B();
assert.ok(b instanceof B);
b = B();
assert.ok(b instanceof B);
});
it('works "new" keyword', function() {
const B = BlogPost;
let b = new B();
assert.ok(b instanceof B);
b = new B();
assert.ok(b instanceof B);
});
});
describe('isNew', function() {
it('is true on instantiation', function() {
const post = new BlogPost();
assert.equal(post.isNew, true);
});
});
it('gh-2140', function() {
db.deleteModel(/Test/);
const S = new Schema({
field: [{ text: String }]
});
const Model = db.model('Test', S);
const s = new Model();
s.field = [null];
s.field = [{ text: 'text' }];
assert.ok(s.field[0]);
});
describe('schema', function() {
it('should exist', function() {
assert.ok(BlogPost.schema instanceof Schema);
assert.ok(BlogPost.prototype.schema instanceof Schema);
});
it('emits init event', function() {
const schema = new Schema({ name: String });
let model;
schema.on('init', function(model_) {
model = model_;
});
db.deleteModel(/Test/);
const Named = db.model('Test', schema);
assert.equal(model, Named);
});
});
describe('structure', function() {
it('default when instantiated', function() {
const post = new BlogPost();
assert.equal(post.db.model('BlogPost').modelName, 'BlogPost');
assert.equal(post.constructor.modelName, 'BlogPost');
assert.ok(post.get('_id') instanceof DocumentObjectId);
assert.equal(post.get('title'), undefined);
assert.equal(post.get('slug'), undefined);
assert.equal(post.get('date'), undefined);
assert.equal(typeof post.get('meta'), 'object');
assert.deepEqual(post.get('meta'), {});
assert.equal(post.get('meta.date'), undefined);
assert.equal(post.get('meta.visitors'), undefined);
assert.equal(post.get('published'), undefined);
assert.equal(Object.keys(post.get('nested')).length, 1);
assert.ok(Array.isArray(post.get('nested').array));
assert.ok(post.get('numbers').isMongooseArray);
assert.ok(post.get('owners').isMongooseArray);
assert.ok(post.get('comments').isMongooseDocumentArray);
assert.ok(post.get('nested.array').isMongooseArray);
});
describe('array', function() {
describe('defaults', function() {
it('to a non-empty array', function() {
const DefaultArraySchema = new Schema({
arr: { type: Array, default: ['a', 'b', 'c'] },
single: { type: Array, default: ['a'] }
});
const DefaultArray = db.model('Test', DefaultArraySchema);
const arr = new DefaultArray();
assert.equal(arr.get('arr').length, 3);
assert.equal(arr.get('arr')[0], 'a');
assert.equal(arr.get('arr')[1], 'b');
assert.equal(arr.get('arr')[2], 'c');
assert.equal(arr.get('single').length, 1);
assert.equal(arr.get('single')[0], 'a');
});
it('empty', function() {
const DefaultZeroCardArraySchema = new Schema({
arr: { type: Array, default: [] },
auto: [Number]
});
const DefaultZeroCardArray = db.model('Test', DefaultZeroCardArraySchema);
const arr = new DefaultZeroCardArray();
assert.equal(arr.get('arr').length, 0);
assert.equal(arr.arr.length, 0);
assert.equal(arr.auto.length, 0);
});
});
});
it('a hash with one null value', function() {
const post = new BlogPost({
title: null
});
assert.strictEqual(null, post.title);
});
it('when saved', async function() {
const post = new BlogPost();
await post.save();
assert.ok(post.get('_id') instanceof DocumentObjectId);
assert.equal(post.get('title'), undefined);
assert.equal(post.get('slug'), undefined);
assert.equal(post.get('date'), undefined);
assert.equal(post.get('published'), undefined);
assert.equal(typeof post.get('meta'), 'object');
assert.deepEqual(post.get('meta'), {});
assert.equal(post.get('meta.date'), undefined);
assert.equal(post.get('meta.visitors'), undefined);
assert.ok(post.get('owners').isMongooseArray);
assert.ok(post.get('comments').isMongooseDocumentArray);
});
describe('init', function() {
it('works', async function() {
const post = new BlogPost();
post.init({
title: 'Test',
slug: 'test',
date: new Date(),
meta: {
date: new Date(),
visitors: 5
},
published: true,
owners: [new DocumentObjectId(), new DocumentObjectId()],
comments: [
{ title: 'Test', date: new Date(), body: 'Test' },
{ title: 'Super', date: new Date(), body: 'Cool' }
]
});
assert.equal(post.get('title'), 'Test');
assert.equal(post.get('slug'), 'test');
assert.ok(post.get('date') instanceof Date);
assert.equal(typeof post.get('meta'), 'object');
assert.ok(post.get('meta').date instanceof Date);
assert.equal(typeof post.get('meta').visitors, 'number');
assert.equal(post.get('published'), true);
assert.equal(post.title, 'Test');
assert.equal(post.slug, 'test');
assert.ok(post.date instanceof Date);
assert.equal(typeof post.meta, 'object');
assert.ok(post.meta.date instanceof Date);
assert.equal(typeof post.meta.visitors, 'number');
assert.equal(post.published, true);
assert.ok(post.get('owners').isMongooseArray);
assert.ok(post.get('owners')[0] instanceof DocumentObjectId);
assert.ok(post.get('owners')[1] instanceof DocumentObjectId);
assert.ok(post.owners.isMongooseArray);
assert.ok(post.owners[0] instanceof DocumentObjectId);
assert.ok(post.owners[1] instanceof DocumentObjectId);
assert.ok(post.get('comments').isMongooseDocumentArray);
assert.ok(post.get('comments')[0] instanceof EmbeddedDocument);
assert.ok(post.get('comments')[1] instanceof EmbeddedDocument);
assert.ok(post.comments.isMongooseDocumentArray);
assert.ok(post.comments[0] instanceof EmbeddedDocument);
assert.ok(post.comments[1] instanceof EmbeddedDocument);
});
it('partially', function() {
const post = new BlogPost();
post.init({
title: 'Test',
slug: 'test',
date: new Date()
});
assert.equal(post.get('title'), 'Test');
assert.equal(post.get('slug'), 'test');
assert.ok(post.get('date') instanceof Date);
assert.equal(typeof post.get('meta'), 'object');
assert.deepEqual(post.get('meta'), {});
assert.equal(post.get('meta.date'), undefined);
assert.equal(post.get('meta.visitors'), undefined);
assert.equal(post.get('published'), undefined);
assert.ok(post.get('owners').isMongooseArray);
assert.ok(post.get('comments').isMongooseDocumentArray);
});
it('with partial hash', function() {
const post = new BlogPost({
meta: {
date: new Date(),
visitors: 5
}
});
assert.equal(post.get('meta.visitors').valueOf(), 5);
});
it('isNew on embedded documents', function() {
const post = new BlogPost();
post.init({
title: 'Test',
slug: 'test',
comments: [{ title: 'Test', date: new Date(), body: 'Test' }]
});
assert.equal(post.get('comments')[0].isNew, false);
});
it('isNew on embedded documents after saving', async function() {
const post = new BlogPost({ title: 'hocus pocus' });
post.comments.push({ title: 'Humpty Dumpty', comments: [{ title: 'nested' }] });
assert.equal(post.get('comments')[0].isNew, true);
assert.equal(post.get('comments')[0].comments[0].isNew, true);
post.invalidate('title'); // force error
await post.save().catch(() => {});
assert.equal(post.isNew, true);
assert.equal(post.get('comments')[0].isNew, true);
assert.equal(post.get('comments')[0].comments[0].isNew, true);
await post.save();
assert.equal(post.isNew, false);
assert.equal(post.get('comments')[0].isNew, false);
assert.equal(post.get('comments')[0].comments[0].isNew, false);
});
});
});
it('collection name can be specified through schema', function() {
const schema = new Schema({ name: String }, { collection: 'tests' });
const Named = mongoose.model('CollectionNamedInSchema1', schema);
assert.equal(Named.prototype.collection.name, 'tests');
const users2schema = new Schema({ name: String }, { collection: 'tests' });
const Named2 = db.model('FooBar', users2schema);
assert.equal(Named2.prototype.collection.name, 'tests');
});
it('saving a model with a null value should perpetuate that null value to the db', async function() {
const post = new BlogPost({
title: null
});
assert.strictEqual(null, post.title);
await post.save();
const check = await BlogPost.findById(post.id);
assert.strictEqual(check.title, null);
});
it('saves subdocuments middleware correctly', async function() {
let child_hook;
let parent_hook;
const childSchema = new Schema({
name: String
});
childSchema.pre('save', function(next) {
child_hook = this.name;
next();
});
const parentSchema = new Schema({
name: String,
children: [childSchema]
});
parentSchema.pre('save', function(next) {
parent_hook = this.name;
next();
});
const Parent = db.model('Parent', parentSchema);
const parent = new Parent({
name: 'Bob',
children: [{
name: 'Mary'
}]
});
const doc = await parent.save();
assert.equal(parent_hook, 'Bob');
assert.equal(child_hook, 'Mary');
doc.children[0].name = 'Jane';
await doc.save();
assert.equal(child_hook, 'Jane');
});
it('instantiating a model with a hash that maps to at least 1 undefined value', async function() {
const post = new BlogPost({
title: undefined
});
assert.strictEqual(undefined, post.title);
await post.save();
const check = await BlogPost.findById(post.id);
assert.strictEqual(check.title, undefined);
});
it('modified nested objects which contain MongoseNumbers should not cause a RangeError on save (gh-714)', async function() {
const schema = new Schema({
nested: {
num: Number
}
});
const M = db.model('Test', schema);
const m = new M();
m.nested = null;
await m.save();
const check = await M.findById(m);
check.nested.num = 5;
const res = await check.save();
assert.ok(res);
});
it('no RangeError on deleteOne() of a doc with Number _id (gh-714)', async function() {
const MySchema = new Schema({
_id: { type: Number },
name: String
});
const MyModel = db.model('Test', MySchema);
const instance = new MyModel({
name: 'test',
_id: 35
});
await instance.save();
const doc = await MyModel.findById(35);
assert.ok(doc);
await doc.deleteOne({});
assert.ok(doc);
});
it('over-writing a number should persist to the db (gh-342)', async function() {
const post = new BlogPost({
meta: {
date: new Date(),
visitors: 10
}
});
const doc = await post.save();
doc.set('meta.visitors', 20);
await doc.save();
const check = await BlogPost.findById(doc.id);
assert.equal(check.get('meta.visitors').valueOf(), 20);
});
describe('methods', function() {
it('can be defined', function() {
const post = new BlogPost();
assert.equal(post.cool(), post);
});
it('can be defined on embedded documents', function() {
const ChildSchema = new Schema({ name: String });
ChildSchema.method('talk', function() {
return 'gaga';
});
const ParentSchema = new Schema({
children: [ChildSchema]
});
const ChildA = db.model('Child', ChildSchema);
const ParentA = db.model('Parent', ParentSchema);
const c = new ChildA();
assert.equal(typeof c.talk, 'function');
const p = new ParentA();
p.children.push({});
assert.equal(typeof p.children[0].talk, 'function');
});
it('can be defined with nested key', function() {
const NestedKeySchema = new Schema({});
NestedKeySchema.method('foo', {
bar: function() {
return this;
}
});
const NestedKey = db.model('Test', NestedKeySchema);
const n = new NestedKey();
assert.equal(n.foo.bar(), n);
});
});
describe('statics', function() {
it('can be defined', function() {
assert.equal(BlogPost.woot(), BlogPost);
});
});
describe('casting as validation errors', function() {
it('error', async function() {
let threw = false;
let post;
try {
post = new BlogPost({ date: 'Test', meta: { date: 'Test' } });
} catch (e) {
threw = true;
}
assert.equal(threw, false);
try {
post.set('title', 'Test');
} catch (e) {
threw = true;
}
assert.equal(threw, false);
const err = await post.save().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
assert.equal(Object.keys(err.errors).length, 2);
post.date = new Date();
post.meta.date = new Date();
await post.save();
});
it('nested error', async function() {
let threw = false;
const post = new BlogPost();
try {
post.init({
meta: {
date: 'Test'
}
});
} catch (e) {
threw = true;
}
assert.equal(threw, false);
try {
post.set('meta.date', 'Test');
} catch (e) {
threw = true;
}
assert.equal(threw, false);
const err = await post.save().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
});
it('subdocument cast error', async function() {
const post = new BlogPost({
title: 'Test',
slug: 'test',
comments: [{ title: 'Test', date: new Date(), body: 'Test' }]
});
post.get('comments')[0].set('date', 'invalid');
const err = await post.save().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
});
it('subdocument validation error', async function() {
function failingvalidator() {
return false;
}
db.deleteModel(/BlogPost/);
const subs = new Schema({
str: {
type: String, validate: failingvalidator
}
});
const BlogPost = db.model('BlogPost', { subs: [subs] });
const post = new BlogPost();
post.init({
subs: [{ str: 'gaga' }]
});
const err = await post.save().then(() => null, err => err);
assert.ok(err instanceof ValidationError);
});
it('subdocument error when adding a subdoc', async function() {
let threw = false;
const post = new BlogPost();
try {
post.get('comments').push({
date: 'Bad date'
});
} catch (e) {
threw = true;
}
assert.equal(threw, false);
const err = await post.save().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
});
it('updates', async function() {
const post = new BlogPost();
post.set('title', '1');
const id = post.get('_id');
const doc = await post.save();
await BlogPost.updateOne({ title: 1, _id: id }, { title: 2 });
const check = await BlogPost.findOne({ _id: doc.get('_id') });
assert.equal(check.get('title'), '2');
});
it('$pull', function() {
const post = new BlogPost();
post.get('numbers').push('3');
assert.equal(post.get('numbers')[0], 3);
});
it('$push', async function() {
const post = new BlogPost();
post.get('numbers').push(1, 2, 3, 4);
const doc = await post.save();
let check = await BlogPost.findById(doc.get('_id'));
assert.equal(check.get('numbers').length, 4);
check.get('numbers').pull('3');
await check.save();
check = await BlogPost.findById(check.get('_id'));
assert.equal(check.get('numbers').length, 3);
});
it('Number arrays', async function() {
const post = new BlogPost();
post.numbers.push(1, '2', 3);
const doc = await post.save();
const check = await BlogPost.findById(doc._id);
assert.ok(~check.numbers.indexOf(1));
assert.ok(~check.numbers.indexOf(2));
assert.ok(~check.numbers.indexOf(3));
});
it('date casting compat with datejs (gh-502)', async function() {
Date.prototype.toObject = function() {
return {
millisecond: 86,
second: 42,
minute: 47,
hour: 17,
day: 13,
week: 50,
month: 11,
year: 2011
};
};
const S = new Schema({
name: String,
description: String,
sabreId: String,
data: {
lastPrice: Number,
comm: String,
curr: String,
rateName: String
},
created: { type: Date, default: Date.now },
valid: { type: Boolean, default: true }
});
const M = db.model('Test', S);
const m = new M();
const doc = await m.save();
assert.ok(doc);
const check = await M.findById(m._id);
await check.save();
assert.ok(check);
await M.deleteOne();
delete Date.prototype.toObject;
});
});
describe('validation', function() {
it('works', async function() {
function dovalidate() {
assert.equal(this.asyncScope, 'correct');
return true;
}
function dovalidateAsync() {
assert.equal(this.scope, 'correct');
return Promise.resolve(true);
}
const TestValidation = db.model('Test', new Schema({
simple: { type: String, required: true },
scope: { type: String, validate: [dovalidate, 'scope failed'], required: true },
asyncScope: { type: String, validate: [dovalidateAsync, 'async scope failed'], required: true }
}));
const post = new TestValidation();
post.set('simple', '');
post.set('scope', 'correct');
post.set('asyncScope', 'correct');
const err = await post.save().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
post.set('simple', 'here');
const doc = await post.save();
assert.ok(doc);
});
it('custom messaging', async function() {
function validate(val) {
return val === 'abc';
}
const TestValidationMessage = db.model('Test', new Schema({
simple: { type: String, validate: [validate, 'must be abc'] }
}));
const post = new TestValidationMessage();
post.set('simple', '');
const err = await post.save().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
assert.ok(err.errors.simple instanceof ValidatorError);
assert.equal(err.errors.simple.message, 'must be abc');
assert.equal(post.errors.simple.message, 'must be abc');
post.set('simple', 'abc');
const doc = await post.save();
assert.ok(doc);
});
it('with Model.schema.path introspection (gh-272)', async function() {
const IntrospectionValidationSchema = new Schema({
name: String
});
const IntrospectionValidation = db.model('Test', IntrospectionValidationSchema);
IntrospectionValidation.schema.path('name').validate(function(value) {
return value.length < 2;
}, 'Name cannot be greater than 1 character for path "{PATH}" with value `{VALUE}`');
const doc = new IntrospectionValidation({ name: 'hi' });
const err = await doc.save().then(() => null, err => err);
assert.equal(err.errors.name.message, 'Name cannot be greater than 1 character for path "name" with value `hi`');
assert.equal(err.name, 'ValidationError');
assert.ok(err.message.indexOf('Test validation failed') !== -1, err.message);
});
it('of required undefined values', async function() {
const TestUndefinedValidation = db.model('Test', new Schema({
simple: { type: String, required: true }
}));
const post = new TestUndefinedValidation();
const err = await post.save().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
post.set('simple', 'here');
const doc = await post.save();
assert.ok(doc);
});
it('save callback should only execute once (gh-319)', async function() {
const D = db.model('Test', new Schema({
username: { type: String, validate: /^[a-z]{6}$/i },
email: { type: String, validate: /^[a-z]{6}$/i },
password: { type: String, validate: /^[a-z]{6}$/i }
}));
const post = new D({
username: 'nope',
email: 'too',
password: 'short'
});
let timesCalled = 0;
const err = await post.save().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
assert.equal(++timesCalled, 1);
assert.equal(Object.keys(err.errors).length, 3);
assert.ok(err.errors.password instanceof ValidatorError);
assert.ok(err.errors.email instanceof ValidatorError);
assert.ok(err.errors.username instanceof ValidatorError);
assert.equal(err.errors.password.message, 'Validator failed for path `password` with value `short`');
assert.equal(err.errors.email.message, 'Validator failed for path `email` with value `too`');
assert.equal(err.errors.username.message, 'Validator failed for path `username` with value `nope`');
assert.equal(Object.keys(post.errors).length, 3);
assert.ok(post.errors.password instanceof ValidatorError);
assert.ok(post.errors.email instanceof ValidatorError);
assert.ok(post.errors.username instanceof ValidatorError);
assert.equal(post.errors.password.message, 'Validator failed for path `password` with value `short`');
assert.equal(post.errors.email.message, 'Validator failed for path `email` with value `too`');
assert.equal(post.errors.username.message, 'Validator failed for path `username` with value `nope`');
});
it('query result', async function() {
const TestV = db.model('Test', new Schema({
resultv: { type: String, required: true }
}));
const post = new TestV();
const err = await post.validate().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
post.resultv = 'yeah';
const doc = await post.save();
const check = await TestV.findOne({ _id: doc._id });
assert.equal(check.resultv, 'yeah');
await check.save();
assert.ok(check);
});
it('of required previously existing null values', async function() {
const TestP = db.model('Test', new Schema({
previous: { type: String, required: true },
a: String
}));
const doc = { a: null, previous: null };
await TestP.collection.insertOne(doc);
const check = await TestP.findOne({ _id: doc._id });
assert.equal(check.isNew, false);
assert.strictEqual(check.get('previous'), null);
const err = await check.validate().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
check.set('previous', 'yoyo');
await check.save();
assert.ok(check);
});
it('nested', async function() {
const TestNestedValidation = db.model('Test', new Schema({
nested: {
required: { type: String, required: true }
}
}));
const post = new TestNestedValidation();
post.set('nested.required', null);
const err = await post.save().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
post.set('nested.required', 'here');
const check = await post.save();
assert.ok(check);
});
it('of nested subdocuments', async function() {
const Subsubdocs = new Schema({ required: { type: String, required: true } });
const Subdocs = new Schema({
required: { type: String, required: true },
subs: [Subsubdocs]
});
const TestSubdocumentsValidation = db.model('Test', new Schema({
items: [Subdocs]
}));
const post = new TestSubdocumentsValidation();
post.get('items').push({ required: '', subs: [{ required: '' }] });
let err = await post.save().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
assert.ok(err.errors['items.0.subs.0.required'] instanceof ValidatorError);
assert.equal(err.errors['items.0.subs.0.required'].message, 'Path `required` is required.');
assert.ok(post.errors['items.0.subs.0.required'] instanceof ValidatorError);
assert.equal(post.errors['items.0.subs.0.required'].message, 'Path `required` is required.');
assert.ok(err.errors['items.0.required']);
assert.ok(post.errors['items.0.required']);
post.items[0].subs[0].set('required', true);
assert.equal(post.$__.validationError, undefined);
err = await post.save().then(() => null, err => err);
assert.ok(err);
assert.ok(err.errors);
assert.ok(err.errors['items.0.required'] instanceof ValidatorError);
assert.equal(err.errors['items.0.required'].message, 'Path `required` is required.');
assert.ok(!err.errors['items.0.subs.0.required']);
assert.ok(!err.errors['items.0.subs.0.required']);
assert.ok(!post.errors['items.0.subs.0.required']);
assert.ok(!post.errors['items.0.subs.0.required']);
post.get('items')[0].set('required', true);
await post.save();
assert.ok(!post.errors);
});
it('without saving', async function() {
const TestCallingValidation = db.model('Test', new Schema({
item: { type: String, required: true }
}));
const post = new TestCallingValidation();
assert.equal(post.schema.path('item').isRequired, true);
assert.strictEqual(post.isNew, true);
const err = await post.validate().then(() => null, err => err);
assert.ok(err instanceof MongooseError);
assert.ok(err instanceof ValidationError);
assert.strictEqual(post.isNew, true);
post.item = 'yo';
await post.validate();
assert.strictEqual(post.isNew, true);
});
it('when required is set to false', function() {
function validator() {
return true;
}
const TestV = db.model('Test', new Schema({
result: { type: String, validate: [validator, 'chump validator'], required: false }
}));
const post = new TestV();