deno.land / x / mongoose@6.7.5 / test / index.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
'use strict';
const sinon = require('sinon');
const start = require('./common');
const assert = require('assert');const random = require('./util').random;const stream = require('stream');const { EventEmitter } = require('events');
const collection = 'blogposts_' + random();
const SetOptionError = require('../lib/error/setOptionError');const mongoose = start.mongoose;const Mongoose = mongoose.Mongoose;const Schema = mongoose.Schema;
const options = {};
describe('mongoose module:', function() { describe('default connection works', function() { it('without options', async function() { const goose = new Mongoose(); const db = goose.connection;
await goose.connect(start.uri, options); await db.close(); });
it('with promise (gh-3790)', async function() { const goose = new Mongoose(); const db = goose.connection;
await goose.connect(start.uri, options);
await db.close(); }); });
it('legacy pluralize by default (gh-5958)', function() { const mongoose = new Mongoose();
mongoose.model('User', new Schema({}));
assert.equal(mongoose.model('User').collection.name, 'users'); });
it('returns legacy pluralize function by default', function() { const legacyPluralize = require('../lib/helpers/pluralize'); const mongoose = new Mongoose();
const pluralize = mongoose.pluralize();
assert.equal(pluralize, legacyPluralize); });
it('sets custom pluralize function (gh-5877)', function() { const mongoose = new Mongoose();
// some custom function of type (str: string) => string const customPluralize = (str) => str; mongoose.pluralize(customPluralize);
const pluralize = mongoose.pluralize(); assert.equal(pluralize, customPluralize);
mongoose.model('User', new Schema({})); assert.equal(mongoose.model('User').collection.name, 'User'); });
it('debug to stream (gh-7018)', async function() { const mongoose = new Mongoose();
const written = []; class StubStream extends stream.Writable { write(chunk) { written.push(chunk); } }
mongoose.set('debug', new StubStream());
const User = mongoose.model('User', new Schema({ name: String }));

await mongoose.connect(start.uri); await User.findOne(); assert.equal(written.length, 1); assert.ok(written[0].startsWith('users.findOne(')); });
it('{g,s}etting options', function() { const mongoose = new Mongoose();
mongoose.set('runValidators', 'b');
assert.equal(mongoose.get('runValidators'), 'b'); assert.equal(mongoose.set('runValidators'), 'b'); });
it('allows `const { model } = mongoose` (gh-3768)', function() { const model = mongoose.model;
model('gh3768', new Schema({ name: String }));
assert.ok(mongoose.models['gh3768']); });
it('options object (gh-8144)', function() { const mongoose = new Mongoose({ bufferCommands: false });
assert.strictEqual(mongoose.options.bufferCommands, false); });
it('bufferCommands option (gh-5879) (gh-9179)', function() { const mongoose = new Mongoose();
mongoose.set('bufferCommands', false);
const M = mongoose.model('Test', new Schema({}));
assert.ok(!M.collection._shouldBufferCommands());
// Allow changing bufferCommands after defining model (gh-9179) mongoose.set('bufferCommands', true); assert.ok(M.collection._shouldBufferCommands());
mongoose.set('bufferCommands', false); assert.ok(!M.collection._shouldBufferCommands()); });
it('cloneSchemas option (gh-6274)', function() { const mongoose = new Mongoose();
mongoose.set('cloneSchemas', true);
const s = new Schema({}); const M = mongoose.model('Test', s); assert.ok(M.schema !== s); assert.doesNotThrow(function() { mongoose.model('Test', M.schema); });
mongoose.set('cloneSchemas', false);
const M2 = mongoose.model('Test2', s); assert.ok(M2.schema === s); });
it('supports disabling `id` via global plugin (gh-10701)', function() { const mongoose = new Mongoose();
mongoose.plugin((schema) => { schema.set('id', false); });
const s = new Schema({}); const M = mongoose.model('Test', s);
assert.equal(M.schema.options.id, false); const doc = new M(); assert.ok(!doc.id); });
it('objectIdGetter option (gh-6588)', function() { const mongoose = new Mongoose();
let o = new mongoose.Types.ObjectId(); assert.strictEqual(o._id, o);
mongoose.set('objectIdGetter', false);
o = new mongoose.Types.ObjectId(); assert.strictEqual(o._id, void 0);
mongoose.set('objectIdGetter', true);
o = new mongoose.Types.ObjectId(); assert.strictEqual(o._id, o); });
it('runValidators option (gh-6865) (gh-6578)', async function() { const mongoose = new Mongoose();
mongoose.set('runValidators', true);
const M = mongoose.model('Test', new Schema({ name: { type: String, required: true } }));
await mongoose.connect(start.uri, options);
const err = await M.updateOne({}, { name: null }).then(() => null, err => err); assert.ok(err.errors['name']);
mongoose.disconnect(); });
it('toJSON options (gh-6815)', function() { const mongoose = new Mongoose();
mongoose.set('toJSON', { virtuals: true });
const schema = new Schema({}); schema.virtual('foo').get(() => 42); const M = mongoose.model('Test', schema);
let doc = new M(); assert.equal(doc.toJSON().foo, 42); assert.equal(doc.toObject().foo, void 0);
assert.equal(doc.toJSON({ virtuals: false }).foo, void 0);
const schema2 = new Schema({}, { toJSON: { virtuals: true } }); schema2.virtual('foo').get(() => 'bar'); const M2 = mongoose.model('Test2', schema2);
doc = new M2(); assert.equal(doc.toJSON({ virtuals: false }).foo, void 0); assert.equal(doc.toJSON().foo, 'bar'); });
it('toObject options (gh-6815)', function() { const mongoose = new Mongoose();
mongoose.set('toObject', { virtuals: true });
const schema = new Schema({}); schema.virtual('foo').get(() => 42); const M = mongoose.model('Test', schema);
const doc = new M(); assert.equal(doc.toObject().foo, 42); assert.strictEqual(doc.toJSON().foo, void 0); });
it('strict option (gh-6858)', function() { const mongoose = new Mongoose();
// With strict: throw, no schema-level override mongoose.set('strict', 'throw');
// `mongoose.Schema` as opposed to just `Schema` matters here because we // a schema pulls the `strict` property default from its Mongoose global. // See gh-7103. We should deprecate default options. let schema = new mongoose.Schema({ name: String }); let M = mongoose.model('gh6858', schema); assert.throws(() => { new M({ name: 'foo', bar: 'baz' }); }, /Field `bar` is not in schema/);
mongoose.deleteModel('gh6858');
// With strict: throw and schema-level override schema = new mongoose.Schema({ name: String }, { strict: true }); M = mongoose.model('gh6858', schema);
let doc = new M({ name: 'foo', bar: 'baz' }); assert.equal(doc.name, 'foo'); assert.strictEqual(doc.bar, void 0); assert.strictEqual(doc.toObject().bar, void 0); assert.strictEqual(doc.$__.strictMode, true);
mongoose.deleteModel('gh6858');
// With strict: false, no schema-level override mongoose.set('strict', false);
schema = new mongoose.Schema({ name: String }); M = mongoose.model('gh6858', schema); doc = new M({ name: 'foo', bar: 'baz' });
assert.strictEqual(doc.$__.strictMode, false);
assert.equal(doc.toObject().bar, 'baz'); });
it('declaring global plugins (gh-5690)', async function() { const mong = new Mongoose(); const subSchema = new Schema({ name: String }); const schema = new Schema({ test: [subSchema] }); let called = 0;
const calls = []; let preSaveCalls = 0; mong.plugin(function(s) { calls.push(s);
s.pre('save', function(next) { ++preSaveCalls; next(); });
s.methods.testMethod = function() { return 42; }; });
schema.plugin(function(s) { assert.equal(s, schema); called++; });
const M = mong.model('GlobalPlugins', schema);
assert.equal(called, 1); assert.equal(calls.length, 2); assert.deepEqual(calls[0].obj, schema.obj); assert.deepEqual(calls[1].obj, subSchema.obj);
assert.equal(preSaveCalls, 0); await mong.connect(start.uri, options);
const doc = await M.create({ test: [{ name: 'Val' }] });
assert.equal(preSaveCalls, 2); assert.equal(doc.testMethod(), 42); assert.equal(doc.test[0].testMethod(), 42); await mong.disconnect(); });
it('declaring global plugins with tags (gh-9780)', async function() { const mong = new Mongoose(); const schema1 = new Schema({}, { pluginTags: ['tag1'] }); const schema2 = new Schema({}, { pluginTags: ['tag2'] }); const schema3 = new Schema({});
mong.plugin(function(s) { s.add({ prop1: String }); }, { tags: ['tag1'] });
mong.plugin(function(s) { s.add({ prop2: String }); }, { tags: ['tag1', 'tag2'] });
mong.plugin(function(s) { s.add({ prop3: String }); });
const Test1 = mong.model('Test1', schema1); const Test2 = mong.model('Test2', schema2); const Test3 = mong.model('Test3', schema3);
assert.ok(Test1.schema.path('prop1')); assert.ok(Test1.schema.path('prop2')); assert.ok(Test1.schema.path('prop3'));
assert.ok(!Test2.schema.path('prop1')); assert.ok(Test2.schema.path('prop2')); assert.ok(Test2.schema.path('prop3'));
assert.ok(!Test3.schema.path('prop1')); assert.ok(!Test3.schema.path('prop2')); assert.ok(Test3.schema.path('prop3')); });
it('global plugins on nested schemas underneath embedded discriminators (gh-7370)', function() { const m = new Mongoose();
const called = []; m.plugin(function(s) { called.push(s); });
const subSchema = new m.Schema({ name: String }, { discriminatorKey: 'kind' }); const schema = new m.Schema({ test: [subSchema] }); const discriminatorNestedSchema = new m.Schema({ other: String }); schema.path('test').discriminator('Foo', new m.Schema({ nested: discriminatorNestedSchema }));
m.model('gh7370', schema); assert.equal(called.length, 3); assert.ok(called.indexOf(discriminatorNestedSchema) !== -1);
return Promise.resolve(); });
it('global plugins with applyPluginsToDiscriminators (gh-7435)', function() { const m = new Mongoose(); m.set('applyPluginsToDiscriminators', true);
const called = []; m.plugin(function(s) { called.push(s); });
const eventSchema = new m.Schema({ kind: { type: String } }, { discriminatorKey: 'kind' });
const testEventSchema = new m.Schema({ inner: { type: new mongoose.Schema({ _id: false, bool: { type: Boolean, required: true } }) } });
const schema = new m.Schema({ events: { type: [eventSchema] } });
schema.path('events').discriminator('test-event', testEventSchema, { clone: false });
m.model('gh7435', schema); assert.equal(called.length, 4); assert.ok(called.indexOf(testEventSchema) !== -1);
return Promise.resolve(); });
it('global plugins recompile schemas (gh-7572)', function() { function helloPlugin(schema) { schema.virtual('greeting').get(() => 'hello'); }
const m = new Mongoose();
m.plugin(helloPlugin);
const nested = new m.Schema({ baz: String }); const outer = new m.Schema({ foo: String, bar: nested });
const Test = m.model('Test', outer); const doc = new Test({ foo: 'abc', bar: { baz: 'def' } });
assert.equal(doc.greeting, 'hello'); assert.equal(doc.bar.greeting, 'hello');
return Promise.resolve(); });
it('top-level ObjectId, Decimal128, Mixed (gh-6760)', function() { const mongoose = new Mongoose();
const schema = new Schema({ testId: mongoose.ObjectId, testNum: mongoose.Decimal128, testMixed: mongoose.Mixed });
const M = mongoose.model('gh6760', schema);
const doc = new M({ testId: 'length12str0', testNum: 123, mixed: {} });
assert.ok(doc.testId instanceof mongoose.Types.ObjectId); assert.ok(doc.testNum instanceof mongoose.Types.Decimal128); });
it('stubbing now() for timestamps (gh-6728)', async function() { const mongoose = new Mongoose();
const date = new Date('2011-06-01');
mongoose.now = () => date;
const schema = new Schema({ name: String }, { timestamps: true });
const M = mongoose.model('gh6728', schema);

await mongoose.connect(start.uri);
const doc = new M({ name: 'foo' });
await doc.save();
assert.equal(doc.createdAt.valueOf(), date.valueOf()); assert.equal(doc.updatedAt.valueOf(), date.valueOf()); });
it('isolates custom types between mongoose instances (gh-6933) (gh-7158)', function() { const m1 = new Mongoose(); const m2 = new Mongoose();
class T1 extends mongoose.SchemaType {} class T2 extends mongoose.SchemaType {}
m1.Schema.Types.T1 = T1; m2.Schema.Types.T2 = T2;
assert.strictEqual(m1.Schema.Types.T1, T1); assert.strictEqual(m2.Schema.Types.T2, T2);
new m1.Schema({ v: T1 }); new m2.Schema({ v: T2 });
return Promise.resolve(); });
it('throws an error on setting invalid options (gh-6899)', function() { try { mongoose.set('someInvalidOption', true); assert.fail('Expected mongoose.set to throw'); } catch (err) { assert.ok(err instanceof SetOptionError); assert.equal(err.message, 'someInvalidOption: "someInvalidOption" is not a valid option to set'); } });
describe('disconnection of all connections', function() { this.timeout(10000);
describe('no callback', function() { it('works', function(done) { const mong = new Mongoose(); let connections = 0; let disconnections = 0; let pending = 4;
mong.connect(start.uri, options); const db = mong.connection;
function cb() { if (--pending) return; assert.equal(connections, 2); assert.equal(disconnections, 2); done(); }
db.on('open', function() { connections++; cb(); });
db.on('close', function() { disconnections++; cb(); });
const events = []; mong.events.on('createConnection', conn => events.push(conn));
const db2 = mong.createConnection(start.uri, options);
assert.equal(events.length, 1); assert.equal(events[0], db2);
db2.on('open', function() { connections++; cb(); });
db2.on('close', function() { disconnections++; cb(); });
mong.disconnect(); }); });
it('with callback', function(done) { const mong = new Mongoose();
mong.connect(start.uri, options);
mong.connection.on('open', function() { mong.disconnect(function() { done(); }); }); });
it('with promise (gh-3790)', function(done) { const _mongoose = new Mongoose();
_mongoose.connect(start.uri, options);
_mongoose.connection.on('open', function() { _mongoose.disconnect().then(function() { done(); }); }); }); });
describe('model()', function() { it('accessing a model that hasn\'t been defined', function() { const mong = new Mongoose(); let thrown = false;
try { mong.model('Test'); } catch (e) { assert.ok(/hasn't been registered/.test(e.message)); thrown = true; }
assert.equal(thrown, true); });
it('returns the model at creation', function() { const Named = mongoose.model('Named', new Schema({ name: String })); const n1 = new Named(); assert.equal(n1.name, null); const n2 = new Named({ name: 'Peter Bjorn' }); assert.equal(n2.name, 'Peter Bjorn');
const schema = new Schema({ number: Number }); const Numbered = mongoose.model('Numbered', schema, collection); const n3 = new Numbered({ number: 1234 }); assert.equal(n3.number.valueOf(), 1234); });
it('prevents overwriting pre-existing models', function() { const m = new Mongoose(); m.model('A', new Schema());
assert.throws(function() { m.model('A', new Schema()); }, /Cannot overwrite `A` model/); });
it('allows passing identical name + schema args', function() { const m = new Mongoose(); const schema = new Schema(); const model = m.model('A', schema);
assert.doesNotThrow(function() { m.model('A', model.schema); });
assert.equal(model, m.model('A', model.schema)); });
it('allows passing identical name+schema+collection args (gh-5767)', function() { const m = new Mongoose(); const schema = new Schema(); const model = m.model('A', schema, 'AA');
assert.doesNotThrow(function() { m.model('A', model.schema, 'AA'); });
assert.equal(model, m.model('A', model.schema, 'AA')); });
it('throws on unknown model name', function() { assert.throws(function() { mongoose.model('iDoNotExist!'); }, /Schema hasn't been registered/); });
describe('passing collection name', function() { describe('when model name already exists', function() { it('returns a new uncached model', function() { const m = new Mongoose(); const s1 = new Schema({ a: [] }); const name = 'Test'; const A = m.model(name, s1); const B = m.model(name); const C = m.model(name, 'alternate'); assert.ok(A.collection.name === B.collection.name); assert.ok(A.collection.name !== C.collection.name); assert.ok(m.models[name].collection.name !== C.collection.name); assert.ok(m.models[name].collection.name === A.collection.name); }); }); });
describe('passing object literal schemas', function() { it('works', function() { const m = new Mongoose(); const A = m.model('A', { n: [{ age: 'number' }] }); const a = new A({ n: [{ age: '47' }] }); assert.strictEqual(47, a.n[0].age); }); }); });
it('clones schema when instance of another Mongoose instance\'s Schema class (gh-11047)', function() { const m = new Mongoose(); const schema = new Schema({ name: String });
const Test = m.connection.model('Test', schema); assert.equal(Test.schema.obj.name, String); });
it('deleteModel()', function() { const mongoose = new Mongoose();
mongoose.model('gh6813', new mongoose.Schema({ name: String }));
assert.ok(mongoose.model('gh6813')); mongoose.deleteModel('gh6813');
assert.throws(function() { mongoose.model('gh6813'); }, /Schema hasn't been registered/);
const Model = mongoose.model('gh6813', new Schema({ name: String })); assert.ok(Model); });
describe('connecting with a signature of uri, options, function', function() { it('with single mongod', async function() { const mong = new Mongoose();
await mong.connect(start.uri, options);
await mong.connection.close(); });
it('with replica set', async function() { const mong = new Mongoose();
if (!start.uri) { return this.skip(); }
await mong.connect(start.uri, options);
await mong.connection.close(); }); });
it('isValidObjectId (gh-3823)', function() { assert.ok(mongoose.isValidObjectId('0123456789ab')); assert.ok(mongoose.isValidObjectId('5f5c2d56f6e911019ec2acdc')); assert.ok(mongoose.isValidObjectId('608DE01F32B6A93BBA314159')); assert.ok(mongoose.isValidObjectId(new mongoose.Types.ObjectId())); assert.ok(mongoose.isValidObjectId(6)); assert.ok(!mongoose.isValidObjectId({ test: 42 })); });
it('isObjectIdOrHexString (gh-11419)', function() { assert.ok(!mongoose.isObjectIdOrHexString('0123456789ab')); assert.ok(mongoose.isObjectIdOrHexString('5f5c2d56f6e911019ec2acdc')); assert.ok(mongoose.isObjectIdOrHexString('608DE01F32B6A93BBA314159')); assert.ok(mongoose.isObjectIdOrHexString(new mongoose.Types.ObjectId())); assert.ok(!mongoose.isObjectIdOrHexString(6)); assert.ok(!mongoose.isValidObjectId({ test: 42 })); });
it('global `strictPopulate` works when false (gh-10694)', async function() { const mongoose = new Mongoose(); mongoose.set('strictPopulate', false); const schema = new mongoose.Schema({ name: String }); const db = await mongoose.connect(start.uri); const Movie = db.model('Movie', schema); const Person = db.model('Person', new mongoose.Schema({ name: String }));
const movie = await Movie.create({ name: 'The Empire Strikes Back' }); await Person.create({ name: 'Test1', favoriteMovie: movie._id }); const entry = await Person.findOne().populate({ path: 'favoriteMovie' }); assert(entry); }); it('global `strictPopulate` works when true (gh-10694)', async function() { const mongoose = new Mongoose(); mongoose.set('strictPopulate', true); const schema = new mongoose.Schema({ name: String }); const db = await mongoose.connect(start.uri); const Movie = db.model('Movie', schema); const Person = db.model('Person', new mongoose.Schema({ name: String }));
const movie = await Movie.create({ name: 'The Empire Strikes Back' }); await Person.create({ name: 'Test1', favoriteMovie: movie._id }); await assert.rejects(async() => { await Person.findOne().populate({ path: 'favoriteGame' }); }, { message: 'Cannot populate path `favoriteGame` because it is not in your schema. Set the `strictPopulate` option to false to override.' }); }); it('allows global `strictPopulate` to be overriden on specific queries set to true (gh-10694)', async function() { const mongoose = new Mongoose(); mongoose.set('strictPopulate', false); const schema = new mongoose.Schema({ name: String }); const db = await mongoose.connect(start.uri); const Movie = db.model('Movie', schema); const Person = db.model('Person', new mongoose.Schema({ name: String })); const movie = await Movie.create({ name: 'The Empire Strikes Back' }); await Person.create({ name: 'Test1', favoriteMovie: movie._id }); await assert.rejects(async() => { await Person.findOne().populate({ path: 'favoriteGame', strictPopulate: true }); }, { message: 'Cannot populate path `favoriteGame` because it is not in your schema. Set the `strictPopulate` option to false to override.' }); }); it('allows global `strictPopulate` to be overriden on specific queries set to false (gh-10694)', async function() { const mongoose = new Mongoose(); mongoose.set('strictPopulate', false); const schema = new mongoose.Schema({ name: String }); const db = await mongoose.connect(start.uri); const Movie = db.model('Movie', schema); const Person = db.model('Person', new mongoose.Schema({ name: String })); const movie = await Movie.create({ name: 'The Empire Strikes Back' }); await Person.create({ name: 'Test1', favoriteMovie: movie._id }); const entry = await Person.findOne().populate({ path: 'favoriteMovie' }); assert(entry); });
describe('exports', function() { function test(mongoose) { assert.equal(typeof mongoose.version, 'string'); assert.equal(typeof mongoose.Mongoose, 'function'); assert.equal(typeof mongoose.Collection, 'function'); assert.equal(typeof mongoose.Connection, 'function'); assert.equal(typeof mongoose.Schema, 'function'); assert.ok(mongoose.Schema.Types); assert.equal(typeof mongoose.SchemaType, 'function'); assert.equal(typeof mongoose.Query, 'function'); assert.equal(typeof mongoose.Promise, 'function'); assert.equal(typeof mongoose.Model, 'function'); assert.equal(typeof mongoose.Document, 'function'); assert.equal(typeof mongoose.Error, 'function'); assert.equal(typeof mongoose.Error.CastError, 'function'); assert.equal(typeof mongoose.Error.ValidationError, 'function'); assert.equal(typeof mongoose.Error.ValidatorError, 'function'); assert.equal(typeof mongoose.Error.VersionError, 'function'); }
it('of module', function() { test(mongoose); });
it('of new Mongoose instances', function() { test(new mongoose.Mongoose()); });
it('of result from .connect() (gh-3940)', async function() { const m = new mongoose.Mongoose(); const resolvedMongoose = await m.connect(start.uri, options);
test(resolvedMongoose); await m.disconnect(); });
it('connect with url doesnt cause unhandled rejection (gh-6997)', async function() { const m = new mongoose.Mongoose(); const _options = Object.assign({}, options, { serverSelectionTimeoutMS: 100 }); const error = await m.connect('mongodb://doesnotexist:27009/test', _options).then(() => null, err => err);
assert.ok(error); });
it('can set `setDefaultsOnInsert` as a global option (gh-9032)', async function() { const m = new mongoose.Mongoose(); m.set('setDefaultsOnInsert', true); const db = await m.connect(start.uri);
const schema = new m.Schema({ title: String, genre: { type: String, default: 'Action' } }, { collection: 'movies_1' });
const Movie = db.model('Movie', schema); await Movie.deleteMany({});
await Movie.updateOne( {}, { title: 'Cloud Atlas' }, { upsert: true } );
// lean is necessary to avoid defaults by casting const movie = await Movie.findOne({ title: 'Cloud Atlas' }).lean(); assert.equal(movie.genre, 'Action'); });
it('setting `setDefaultOnInsert` on operation has priority over base option (gh-9032)', async function() { const m = new mongoose.Mongoose(); m.set('setDefaultsOnInsert', true);
const db = await m.connect(start.uri);
const schema = new m.Schema({ title: String, genre: { type: String, default: 'Action' } }, { collection: 'movies_2' });
const Movie = db.model('Movie', schema);

await Movie.updateOne( {}, { title: 'The Man From Earth' }, { upsert: true, setDefaultsOnInsert: false } );
// lean is necessary to avoid defaults by casting const movie = await Movie.findOne({ title: 'The Man From Earth' }).lean(); assert.ok(!movie.genre); }); it('should prevent non-hexadecimal strings (gh-9996)', function() { const badIdString = 'z'.repeat(24); assert.deepStrictEqual(mongoose.isValidObjectId(badIdString), false); const goodIdString = '1'.repeat(24); assert.deepStrictEqual(mongoose.isValidObjectId(goodIdString), true); const goodIdString2 = '1'.repeat(12); assert.deepStrictEqual(mongoose.isValidObjectId(goodIdString2), true); }); it('Allows a syncIndexes shorthand mongoose.syncIndexes (gh-10893)', async function() { const m = new mongoose.Mongoose(); assert.deepEqual(await m.syncIndexes(), {}); });
it('Allows for the removal of indexes via string or object (gh-11547)', async function() { const schema = new Schema({ title: String, weight: Number, age: Number, name: String, location: String });
schema.index({ title: 1 }, { name: 'title index' }); schema.index({ weight: 1 }); schema.index({ age: 1, name: 1 }); schema.index({ location: 1 }); assert.equal(schema._indexes.length, 4);
schema.removeIndex('title index'); assert.equal(schema.indexes().length, 3); assert.deepStrictEqual( schema.indexes().map(i => i[0]), [{ weight: 1 }, { age: 1, name: 1 }, { location: 1 }] );
schema.removeIndex({ age: 1, name: 1 }); assert.equal(schema.indexes().length, 2); assert.deepStrictEqual( schema.indexes().map(i => i[0]), [{ weight: 1 }, { location: 1 }] );
schema.removeIndex({ weight: 1 }); assert.equal(schema.indexes().length, 1); assert.deepStrictEqual(schema.indexes().map(i => i[0]), [{ location: 1 }]);
schema.clearIndexes(); assert.equal(schema.indexes().length, 0); });
describe('global `allowDiskUse` (gh-11478)', () => { this.afterEach(() => sinon.restore());
it('is `undefined` by default', async() => { // Arrange const m = new mongoose.Mongoose();
const db = await m.connect(start.uri);
const userSchema = new m.Schema({ name: String });
const User = db.model('User', userSchema);
const nativeAggregateSpy = sinon.spy(User.collection, 'aggregate');
// Act await User.aggregate([{ $match: {} }]);
// Assert const optionsSentToMongo = nativeAggregateSpy.args[0][1]; assert.strictEqual(optionsSentToMongo.allowDiskUse, undefined); });
it('works when set to `true` and no option provided', async() => { // Arrange const m = new mongoose.Mongoose(); m.set('allowDiskUse', true);
const db = await m.connect(start.uri);
const userSchema = new m.Schema({ name: String });
const User = db.model('User', userSchema); const nativeAggregateSpy = sinon.spy(User.collection, 'aggregate');
// Act await User.aggregate([{ $match: {} }]);
// Assert const optionsSentToMongo = nativeAggregateSpy.args[0][1]; assert.strictEqual(optionsSentToMongo.allowDiskUse, true); }); it('can be overridden by a specific query', async() => { // Arrange const m = new mongoose.Mongoose(); m.set('allowDiskUse', true);
const db = await m.connect(start.uri);
const userSchema = new m.Schema({ name: String });
const User = db.model('User', userSchema); const nativeAggregateSpy = sinon.spy(User.collection, 'aggregate');
// Act await User.aggregate([{ $match: {} }]).allowDiskUse(false);
// Assert const optionsSentToMongo = nativeAggregateSpy.args[0][1]; assert.equal(optionsSentToMongo.allowDiskUse, false); }); }); describe('global `timestamps.createdAt.immutable` (gh-10139)', () => { it('is `true` by default', () => { // Arrange const m = new mongoose.Mongoose();
// Act const userSchema = new m.Schema({ name: String }, { timestamps: true });
// Assert assert.equal(userSchema.path('createdAt').options.immutable, true); });
it('can be overridden to `false`', () => { // Arrange const m = new mongoose.Mongoose(); m.set('timestamps.createdAt.immutable', false);
// Act const userSchema = new m.Schema({ name: String }, { timestamps: true });
// Assert assert.equal(userSchema.path('createdAt').options.immutable, false); }); }); });
describe('custom drivers', function() { it('can set custom driver (gh-11900)', async function() { const m = new mongoose.Mongoose();
class Collection { findOne(filter, options, cb) { cb(null, { answer: 42 }); } } class Connection extends EventEmitter { constructor(base) { super(); this.base = base; this.models = {}; }
collection() { return new Collection(); }
openUri(uri, opts, callback) { this.readyState = mongoose.ConnectionStates.connected; callback(); } } const driver = { Collection, getConnection: () => Connection };
m.setDriver(driver);
await m.connect();
const Test = m.model('Test', m.Schema({ answer: Number }));
const res = await Test.findOne(); assert.deepEqual(res.toObject(), { answer: 42 }); }); }); describe('global id option', function() { it('can disable the id virtual on schemas gh-11966', async function() { const m = new mongoose.Mongoose(); m.set('id', false);
const db = await m.connect(start.uri);
const schema = new m.Schema({ title: String });
const falseID = db.model('gh11966', schema);

const entry = await falseID.create({ title: 'The IDless master' }); assert.equal(entry.id, undefined); }); });
describe('set()', function() { let m;
beforeEach(() => { m = new mongoose.Mongoose(); });
it('should be able to set a option through set with (key, value)', function() { // also test the getter behavior of the function assert.strictEqual(m.options['debug'], undefined); assert.strictEqual(m.set('debug'), undefined); m.set('debug', true);
assert.strictEqual(m.options['debug'], true); assert.strictEqual(m.set('debug'), true); });
it('should be able to set a option through a object with {key: value}', function() { assert.strictEqual(m.options['debug'], undefined); m.set({ debug: true });
assert.strictEqual(m.options['debug'], true); });
it('should throw a single error when using a invalid key', function() { try { m.set('invalid', true); assert.fail('Expected .set to throw'); } catch (err) { assert.ok(err instanceof SetOptionError); assert.strictEqual(Object.keys(err.errors).length, 1); assert.strictEqual(err.message, 'invalid: "invalid" is not a valid option to set'); } });
it('should throw a error with many errors when using multiple invalid keys', function() { try { m.set({ invalid1: true, invalid2: true }); assert.fail('Expected .set to throw'); } catch (err) { assert.ok(err instanceof SetOptionError); assert.strictEqual(Object.keys(err.errors).length, 2); assert.strictEqual(err.message, 'invalid1: "invalid1" is not a valid option to set, invalid2: "invalid2" is not a valid option to set'); assert.ok(err.errors['invalid1'] instanceof SetOptionError.SetOptionInnerError); assert.strictEqual(err.errors['invalid1'].message, '"invalid1" is not a valid option to set'); assert.ok(err.errors['invalid2'] instanceof SetOptionError.SetOptionInnerError); assert.strictEqual(err.errors['invalid2'].message, '"invalid2" is not a valid option to set'); } });
it('should apply all values, even if there are errors', function() { assert.strictEqual(m.options['debug'], undefined); try { m.set({ invalid: true, debug: true }); assert.fail('Expected .set to throw'); } catch (err) { assert.ok(err instanceof SetOptionError); assert.ok(err.errors['invalid'] instanceof SetOptionError.SetOptionInnerError); assert.strictEqual(err.message, 'invalid: "invalid" is not a valid option to set'); assert.strictEqual(m.options['debug'], true); } });
it('should throw a single error when using a invalid key when getting', function() { try { m.set('invalid'); assert.fail('Expected .set to throw'); } catch (err) { assert.ok(err instanceof SetOptionError); assert.ok(err.errors['invalid'] instanceof SetOptionError.SetOptionInnerError); assert.strictEqual(err.message, 'invalid: "invalid" is not a valid option to set'); } }); });});
mongoose

Version Info

Tagged at
a year ago