-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathconnection.test.js
1554 lines (1256 loc) · 48.8 KB
/
connection.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';
/**
* Module dependencies.
*/
const start = require('./common');
const Promise = require('bluebird');
const Q = require('q');
const assert = require('assert');
const sinon = require('sinon');
const mongodb = require('mongodb');
const MongooseError = require('../lib/error/index');
const mongoose = start.mongoose;
const Schema = mongoose.Schema;
/**
* Test.
*/
describe('connections:', function() {
this.timeout(10000);
describe('openUri (gh-5304)', function() {
it('with mongoose.createConnection()', function() {
const conn = mongoose.createConnection(start.uri.slice(0, start.uri.lastIndexOf('/')) + '/' + start.databases[0]);
assert.equal(conn.constructor.name, 'NativeConnection');
const Test = conn.model('Test', new Schema({ name: String }));
assert.equal(Test.modelName, 'Test');
const findPromise = Test.findOne();
return conn.asPromise().
then(function(conn) {
assert.equal(conn.constructor.name, 'NativeConnection');
// the regex below extract the first ip & port, because the created connection's properties only have the first anyway as "host" and "port"
const match = /mongodb:\/\/([\d.]+)(?::(\d+))?(?:,[\d.]+(?::\d+)?)*\/(\w+)/i.exec(start.uri);
assert.ok(match);
assert.equal(conn.host, match[1]);
assert.equal(conn.port, parseInt(match[2]));
assert.equal(conn.name, start.databases[0]);
return findPromise;
}).
then(function() {
return conn.close();
});
});
it('with autoIndex (gh-5423)', async function() {
const conn = await mongoose.createConnection(start.uri, {
autoIndex: false
}).asPromise();
assert.strictEqual(conn.config.autoIndex, false);
await conn.close();
});
it('with autoCreate (gh-6489)', async function() {
const conn = await mongoose.createConnection(start.uri, {
// autoCreate: true
}).asPromise();
const Model = conn.model('gh6489_Conn', new Schema({ name: String }, {
collation: { locale: 'en_US', strength: 1 },
collection: 'gh6489_Conn'
}));
await Model.init();
// Will throw if collection was not created
const collections = await conn.db.listCollections().toArray();
assert.ok(collections.map(c => c.name).includes('gh6489_Conn'));
await Model.create([{ name: 'alpha' }, { name: 'Zeta' }]);
// Ensure that the default collation is set. Mongoose will set the
// collation on the query itself (see gh-4839).
const res = await conn.collection('gh6489_Conn').
find({}).sort({ name: 1 }).toArray();
assert.deepEqual(res.map(v => v.name), ['alpha', 'Zeta']);
await conn.close();
});
it('with autoCreate = false (gh-8814)', async function() {
const conn = await mongoose.createConnection(start.uri, {
autoCreate: false
}).asPromise();
const Model = conn.model('gh8814_Conn', new Schema({ name: String }, {
collation: { locale: 'en_US', strength: 1 },
collection: 'gh8814_Conn'
}));
await Model.init();
const res = await conn.db.listCollections().toArray();
assert.ok(!res.map(c => c.name).includes('gh8814_Conn'));
await conn.close();
});
it('autoCreate when collection already exists does not fail (gh-7122)', async function() {
const conn = await mongoose.createConnection(start.uri).asPromise();
const schema = new mongoose.Schema({
name: {
type: String,
index: { unique: true }
}
}, { autoCreate: true });
await conn.model('Actor', schema).init();
await conn.close();
});
it('throws helpful error with legacy syntax (gh-6756)', function() {
assert.throws(function() {
mongoose.createConnection('127.0.0.1', 'dbname', 27017);
}, /mongoosejs\.com.*connections\.html/);
});
it('throws helpful error with undefined uri (gh-6763)', function() {
assert.throws(function() {
mongoose.createConnection(void 0);
}, /string.*createConnection/);
});
it('resolving with q (gh-5714)', async function() {
const bootMongo = Q.defer();
const conn = mongoose.createConnection(start.uri);
conn.on('connected', function() {
bootMongo.resolve(this);
});
const _conn = await bootMongo.promise;
assert.equal(_conn, conn);
await conn.close();
});
it('connection plugins (gh-7378)', async function() {
const conn1 = mongoose.createConnection(start.uri);
const conn2 = mongoose.createConnection(start.uri);
const called = [];
conn1.plugin(schema => called.push(schema));
conn2.model('Test', new Schema({}));
assert.equal(called.length, 0);
const schema = new Schema({});
conn1.model('Test', schema);
assert.equal(called.length, 1);
assert.equal(called[0], schema);
await conn1.close();
await conn2.close();
});
});
describe('helpers', function() {
let conn;
before(function() {
conn = mongoose.createConnection(start.uri2);
return conn;
});
after(function() {
return conn.close();
});
it('dropDatabase()', async function() {
await conn.dropDatabase();
});
it('dropCollection()', async function() {
await conn.db.collection('test').insertOne({ x: 1 });
await conn.dropCollection('test');
const doc = await conn.db.collection('test').findOne();
assert.ok(!doc);
});
it('createCollection()', async function() {
await conn.dropDatabase();
await conn.createCollection('gh5712', {
capped: true,
size: 1024
});
const collections = await conn.db.listCollections().toArray();
const names = collections.map(function(c) { return c.name; });
assert.ok(names.indexOf('gh5712') !== -1);
assert.ok(collections[names.indexOf('gh5712')].options.capped);
await conn.createCollection('gh5712_0');
const collectionsAfterCreation = await conn.db.listCollections().toArray();
const newCollectionsNames = collectionsAfterCreation.map(function(c) { return c.name; });
assert.ok(newCollectionsNames.indexOf('gh5712') !== -1);
});
});
it('should allow closing a closed connection', async function() {
const db = mongoose.createConnection();
assert.equal(db.readyState, 0);
await db.close();
});
describe('errors', function() {
it('.catch() means error does not get thrown (gh-5229)', function(done) {
const db = mongoose.createConnection();
db.openUri('fail connection').catch(function(error) {
assert.ok(error);
done();
});
});
it('promise is rejected even if there is an error event listener (gh-7850)', function(done) {
const db = mongoose.createConnection();
let called = 0;
db.on('error', () => ++called);
db.openUri('fail connection').catch(function(error) {
assert.ok(error);
setTimeout(() => {
assert.equal(called, 1);
done();
}, 0);
});
});
it('readyState is disconnected if initial connection fails (gh-6244)', async function() {
const db = mongoose.createConnection();
let threw = false;
try {
await db.openUri('fail connection');
} catch (err) {
assert.ok(err);
assert.equal(err.name, 'MongoParseError');
threw = true;
}
assert.ok(threw);
assert.strictEqual(db.readyState, 0);
});
});
describe('connect callbacks', function() {
it('should return an error if malformed uri passed', function(done) {
const db = mongoose.createConnection('mongodb:///fake', {}, function(err) {
assert.equal(err.name, 'MongoParseError');
done();
});
db.close();
assert.ok(!db.options);
});
});
describe('.model()', function() {
let db;
before(function() {
db = start();
});
after(async function() {
await db.close();
});
beforeEach(function() {
db.deleteModel(/.*/);
});
it('allows passing a schema', function() {
mongoose.deleteModel(/Test/);
const MyModel = mongoose.model('Test', new Schema({
name: String
}));
assert.ok(MyModel.schema instanceof Schema);
assert.ok(MyModel.prototype.schema instanceof Schema);
const m = new MyModel({ name: 'aaron' });
assert.equal(m.name, 'aaron');
});
it('should properly assign the db', function() {
const A = mongoose.model('testing853a', new Schema({ x: String }), 'testing853-1');
const B = mongoose.model('testing853b', new Schema({ x: String }), 'testing853-2');
const C = B.model('testing853a');
assert.ok(C === A);
});
it('prevents overwriting pre-existing models', function() {
db.deleteModel(/Test/);
db.model('Test', new Schema());
assert.throws(function() {
db.model('Test', new Schema());
}, /Cannot overwrite `Test` model/);
});
it('allows passing identical name + schema args', function() {
const name = 'Test';
const schema = new Schema();
db.deleteModel(/Test/);
const model = db.model(name, schema);
db.model(name, model.schema);
});
it('throws on unknown model name', function() {
assert.throws(function() {
db.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 s1 = new Schema({ a: [] });
const name = 'Test';
const A = db.model(name, s1);
const B = db.model(name);
const C = db.model(name, 'alternate');
assert.ok(A.collection.name === B.collection.name);
assert.ok(A.collection.name !== C.collection.name);
assert.ok(db.models[name].collection.name !== C.collection.name);
assert.ok(db.models[name].collection.name === A.collection.name);
});
});
});
describe('passing object literal schemas', function() {
it('works', function(done) {
const A = db.model('A', { n: [{ age: 'number' }] });
const a = new A({ n: [{ age: '47' }] });
assert.strictEqual(47, a.n[0].age);
a.save(function(err) {
assert.ifError(err);
A.findById(a, function(err) {
assert.ifError(err);
assert.strictEqual(47, a.n[0].age);
done();
});
});
});
});
});
it('force close (gh-5664)', function(done) {
const opts = {};
const db = mongoose.createConnection(start.uri, opts);
const coll = db.collection('Test');
db.asPromise().then(function() {
setTimeout(function() {
coll.insertOne({ x: 1 }, function(error) {
assert.ok(error);
done();
});
}, 100);
// Force close
db.close(true);
});
});
it('destroy connection and remove it permanantly', (done) => {
const opts = {};
const conn = mongoose.createConnection(start.uri, opts);
const MongoClient = mongodb.MongoClient;
const stub = sinon.stub(MongoClient.prototype, 'close').callsFake((force, callback) => {
callback();
});
conn.useDb('test-db');
const totalConn = mongoose.connections.length;
conn.destroy(() => {
assert.equal(mongoose.connections.length, totalConn - 1);
stub.restore();
done();
});
});
it('verify that attempt to re-open destroyed connection throws error, via promise', (done) => {
const opts = {};
const conn = mongoose.createConnection(start.uri, opts);
const MongoClient = mongodb.MongoClient;
const stub = sinon.stub(MongoClient.prototype, 'close').callsFake((force, callback) => {
callback();
});
conn.useDb('test-db');
conn.destroy(async() => {
try {
await conn.openUri(start.uri);
} catch (error) {
assert.equal(error.message, 'Connection has been closed and destroyed, and cannot be used for re-opening the connection. Please create a new connection with `mongoose.createConnection()` or `mongoose.connect()`.');
stub.restore();
done();
}
});
});
it('verify that attempt to re-open destroyed connection throws error, via callback', (done) => {
const opts = {};
const conn = mongoose.createConnection(start.uri, opts);
const MongoClient = mongodb.MongoClient;
const stub = sinon.stub(MongoClient.prototype, 'close').callsFake((force, callback) => {
callback();
});
conn.useDb('test-db');
conn.destroy(() => {
conn.openUri(start.uri, function(error, result) {
assert.equal(result, undefined);
assert.equal(error, 'Connection has been closed and destroyed, and cannot be used for re-opening the connection. Please create a new connection with `mongoose.createConnection()` or `mongoose.connect()`.');
stub.restore();
done();
});
});
});
it('force close with connection created after close (gh-5664)', function(done) {
const opts = {};
const db = mongoose.createConnection(start.uri, opts);
db.asPromise().then(function() {
setTimeout(function() {
let threw = false;
try {
db.collection('Test').insertOne({ x: 1 });
} catch (error) {
threw = true;
assert.ok(error);
}
assert.ok(threw);
done();
}, 100);
// Force close
db.close(true);
});
});
it('bufferCommands (gh-5720)', function() {
let opts = { bufferCommands: false };
let db = mongoose.createConnection(start.uri, opts);
let M = db.model('gh5720', new Schema({}));
assert.ok(!M.collection._shouldBufferCommands());
db.close();
opts = { bufferCommands: true };
db = mongoose.createConnection(start.uri, opts);
M = db.model('gh5720', new Schema({}, { bufferCommands: false }));
assert.ok(!M.collection._shouldBufferCommands());
db.close();
opts = { bufferCommands: true };
db = mongoose.createConnection(start.uri, opts);
M = db.model('gh5720', new Schema({}));
assert.ok(M.collection._shouldBufferCommands());
db = mongoose.createConnection();
M = db.model('gh5720', new Schema({}));
opts = { bufferCommands: false };
db.openUri(start.uri, opts);
assert.ok(!M.collection._shouldBufferCommands());
return M.findOne().then(() => assert.ok(false), err => assert.ok(err.message.includes('initial connection'))).
then(() => db.close());
});
it('dbName option (gh-6106)', function() {
const opts = { dbName: 'bacon' };
return mongoose.
createConnection(start.uri, opts).
asPromise().
then(db => {
assert.equal(db.name, 'bacon');
db.close();
});
});
it('uses default database in uri if options.dbName is not provided', function() {
return mongoose.createConnection(start.uri.slice(0, start.uri.lastIndexOf('/')) + '/default-db-name').
asPromise().
then(db => {
assert.equal(db.name, 'default-db-name');
db.close();
});
});
it('startSession() (gh-6653)', function() {
const conn = mongoose.createConnection(start.uri);
let lastUse;
let session;
return conn.startSession().
then(_session => {
session = _session;
assert.ok(session);
lastUse = session.serverSession.lastUse;
return new Promise(resolve => setTimeout(resolve, 1));
}).then(() => {
return conn.model('Test', new Schema({})).findOne({}, null, { session });
}).
then(() => {
assert.ok(session.serverSession.lastUse > lastUse);
return conn.close();
});
});
describe('modelNames()', function() {
it('returns names of all models registered on it', async function() {
const m = new mongoose.Mongoose();
m.model('root', { x: String });
const another = m.model('another', { x: String });
another.discriminator('discriminated', new Schema({ x: String }));
const db = m.createConnection();
db.model('something', { x: String });
let names = db.modelNames();
assert.ok(Array.isArray(names));
assert.equal(names.length, 1);
assert.equal(names[0], 'something');
names = m.modelNames();
assert.ok(Array.isArray(names));
assert.equal(names.length, 3);
assert.equal(names[0], 'root');
assert.equal(names[1], 'another');
assert.equal(names[2], 'discriminated');
await db.close();
});
});
describe('connection pool sharing: ', function() {
it('works', async function() {
const db = mongoose.createConnection(start.uri);
const db2 = db.useDb('mongoose2');
assert.equal('mongoose2', db2.name);
assert.equal(db2.port, db.port);
assert.equal(db2.replica, db.replica);
assert.equal(db2.hosts, db.hosts);
assert.equal(db2.host, db.host);
assert.equal(db2.port, db.port);
assert.equal(db2.user, db.user);
assert.equal(db2.pass, db.pass);
assert.deepEqual(db.options, db2.options);
await db2.close();
});
it('saves correctly', async function() {
const db = start();
const db2 = db.useDb(start.databases[1]);
const schema = new Schema({
body: String,
thing: Number
});
const m1 = db.model('Test', schema);
const m2 = db2.model('Test', schema);
const i1 = await m1.create({ body: 'this is some text', thing: 1 });
const i2 = await m2.create({ body: 'this is another body', thing: 2 });
const item1 = await m1.findById(i1.id);
assert.equal('this is some text', item1.body);
assert.equal(1, item1.thing);
const item2 = await m2.findById(i2.id);
assert.equal('this is another body', item2.body);
assert.equal(2, item2.thing);
// validate the doc doesn't exist in the other db
const nothing = await m1.findById(i2.id);
assert.strictEqual(null, nothing);
const nothing2 = await m2.findById(i1.id);
assert.strictEqual(null, nothing2);
await db.close();
await db2.close();
});
it('emits connecting events on both', async function() {
const db = mongoose.createConnection();
const db2 = db.useDb(start.databases[1]);
let hit = false;
db2.on('connecting', async function() {
hit && await close();
hit = true;
});
db.on('connecting', async function() {
hit && await close();
hit = true;
});
db.openUri(start.uri);
async function close() {
await db.close();
}
});
it('emits connected events on both', function() {
const db = mongoose.createConnection();
const db2 = db.useDb(start.databases[1]);
let hit = false;
db2.on('connected', function() {
hit && close();
hit = true;
});
db.on('connected', function() {
hit && close();
hit = true;
});
db.openUri(start.uri);
async function close() {
await db.close();
}
});
it('emits open events on both', function() {
const db = mongoose.createConnection();
const db2 = db.useDb(start.databases[1]);
let hit = false;
db2.on('open', function() {
hit && close();
hit = true;
});
db.on('open', function() {
hit && close();
hit = true;
});
db.openUri(start.uri);
async function close() {
await db.close();
}
});
it('emits disconnecting events on both, closing initial db', function(done) {
const db = mongoose.createConnection();
const db2 = db.useDb(start.databases[1]);
let hit = false;
db2.on('disconnecting', function() {
hit && done();
hit = true;
});
db.on('disconnecting', function() {
hit && done();
hit = true;
});
db.on('open', function() {
db.close();
});
db.openUri(start.uri);
});
it('emits disconnecting events on both, closing secondary db', function(done) {
const db = mongoose.createConnection();
const db2 = db.useDb(start.databases[1]);
let hit = false;
db2.on('disconnecting', function() {
hit && done();
hit = true;
});
db.on('disconnecting', function() {
hit && done();
hit = true;
});
db.on('open', function() {
db2.close();
});
db.openUri(start.uri);
});
it('emits disconnected events on both, closing initial db', function(done) {
const db = mongoose.createConnection();
const db2 = db.useDb(start.databases[1]);
let hit = false;
db2.on('disconnected', function() {
hit && done();
hit = true;
});
db.on('disconnected', function() {
hit && done();
hit = true;
});
db.on('open', function() {
db.close();
});
db.openUri(start.uri);
});
it('emits disconnected events on both, closing secondary db', function(done) {
const db = mongoose.createConnection();
const db2 = db.useDb(start.databases[1]);
let hit = false;
db2.on('disconnected', function() {
hit && done();
hit = true;
});
db.on('disconnected', function() {
hit && done();
hit = true;
});
db.on('open', function() {
db2.close();
});
db.openUri(start.uri);
});
it('closes correctly for all dbs, closing initial db', async function() {
const db = await start({ noErrorListener: true }).asPromise();
const db2 = db.useDb(start.databases[1]);
const p = new Promise(resolve => {
db2.on('close', function() {
resolve();
});
});
await db.close();
await p;
});
it('handles re-opening base connection (gh-11240)', async function() {
const db = await start().asPromise();
const db2 = db.useDb(start.databases[1]);
await db.close();
await db.openUri(start.uri);
assert.strictEqual(db.client, db2.client);
await db.close();
});
it('closes correctly for all dbs, closing secondary db', function(done) {
const db = start();
const db2 = db.useDb(start.databases[1]);
db.on('disconnected', function() {
done();
});
db2.close();
});
it('cache connections to the same db', function() {
const db = start();
const db2 = db.useDb(start.databases[1], { useCache: true });
const db3 = db.useDb(start.databases[1], { useCache: true });
assert.strictEqual(db2, db3);
return db.close();
});
});
describe('shouldAuthenticate()', function() {
describe('when using standard authentication', function() {
describe('when username and password are undefined', function() {
it('should return false', function() {
const db = mongoose.createConnection(start.uri, {});
assert.equal(db.shouldAuthenticate(), false);
return db.close();
});
});
describe('when username and password are empty strings', function() {
it('should return false', function() {
const db = mongoose.createConnection(start.uri, {
user: '',
pass: ''
});
db.on('error', function() {});
assert.equal(db.shouldAuthenticate(), false);
return db.close();
});
});
describe('when both username and password are defined', function() {
it('should return true', function() {
const db = mongoose.createConnection(start.uri, {
user: 'user',
pass: 'pass'
});
db.asPromise().catch(() => {});
assert.equal(db.shouldAuthenticate(), true);
db.close(); // does not actually do anything
});
});
});
describe('when using MONGODB-X509 authentication', function() {
describe('when username and password are undefined', function() {
it('should return false', function() {
const db = mongoose.createConnection(start.uri, {});
db.on('error', function() {
});
assert.equal(db.shouldAuthenticate(), false);
return db.close();
});
});
describe('when only username is defined', function() {
it('should return false', function() {
const db = mongoose.createConnection(start.uri, {
user: 'user',
auth: { authMechanism: 'MONGODB-X509' }
});
db.asPromise().catch(() => {});
assert.equal(db.shouldAuthenticate(), true);
db.close(); // does not actually do anything
});
});
describe('when both username and password are defined', function() {
it('should return false', function() {
const db = mongoose.createConnection(start.uri, {
user: 'user',
pass: 'pass',
auth: { authMechanism: 'MONGODB-X509' }
});
db.asPromise().catch(() => {});
assert.equal(db.shouldAuthenticate(), true);
db.close(); // does not actually do anything
});
});
});
});
describe('passing a function into createConnection', function() {
it('should store the name of the function (gh-6517)', function(done) {
const conn = mongoose.createConnection(start.uri);
const schema = new Schema({ name: String });
class Person extends mongoose.Model {}
conn.model(Person, schema);
assert.strictEqual(conn.modelNames()[0], 'Person');
conn.close(done);
});
});
it('deleteModel()', async function() {
const conn = mongoose.createConnection(start.uri);
let Model = conn.model('gh6813', new Schema({ name: String }));
const events = [];
conn.on('deleteModel', model => events.push(model));
assert.ok(conn.model('gh6813'));
conn.deleteModel('gh6813');
assert.equal(events.length, 1);
assert.equal(events[0], Model);
assert.throws(function() {
conn.model('gh6813');
}, /Schema hasn't been registered/);
Model = conn.model('gh6813', new Schema({ name: String }));
assert.ok(Model);
await Model.create({ name: 'test' });
await conn.close();
});
it('throws a MongooseServerSelectionError on server selection timeout (gh-8451)', function() {
const opts = {
serverSelectionTimeoutMS: 100
};
const uri = 'mongodb://baddomain:27017/test';
return mongoose.createConnection(uri, opts).asPromise().then(() => assert.ok(false), err => {
assert.equal(err.name, 'MongooseServerSelectionError');
});
});
it('`watch()` on a whole collection (gh-8425)', async function() {
this.timeout(10000);
if (!process.env.REPLICA_SET) {
this.skip();
}
const opts = {
replicaSet: process.env.REPLICA_SET
};
const conn = await mongoose.createConnection(start.uri, opts);
const Model = conn.model('Test', Schema({ name: String }));
await Model.create({ name: 'test' });
const changeStream = conn.watch();
const changes = [];
changeStream.on('change', data => {
changes.push(data);
});
await new Promise((resolve) => changeStream.on('ready', () => resolve()));
const nextChange = new Promise(resolve => changeStream.on('change', resolve));
await Model.create({ name: 'test2' });
await nextChange;
assert.equal(changes.length, 1);
assert.equal(changes[0].operationType, 'insert');
await conn.close();
});
it('useDB inherits config from default connection (gh-8267)', async function() {
const m = new mongoose.Mongoose();
await m.connect(start.uri, { sanitizeFilter: true });
const db2 = m.connection.useDb('gh8267-1');
assert.equal(db2.config.sanitizeFilter, true);
await m.disconnect();
});
it('allows setting client on a disconnected connection (gh-9164)', async function() {
const client = await mongodb.MongoClient.connect(start.uri);
const conn = mongoose.createConnection().setClient(client);
assert.equal(conn.readyState, 1);
await conn.createCollection('test');
const res = await conn.dropCollection('test');
assert.ok(res);
await conn.close();
});
it('connection.asPromise() resolves to a connection instance (gh-9496)', async function() {
const m = new mongoose.Mongoose();
m.connect(start.uri);
const conn = await m.connection.asPromise();
assert.ok(conn instanceof m.Connection);
assert.ok(conn);
});
it('allows overwriting models (gh-9406)', function() {
const m = new mongoose.Mongoose();
const events = [];
m.connection.on('model', model => events.push(model));
const M1 = m.model('Test', Schema({ name: String }), null, { overwriteModels: true });
assert.equal(events.length, 1);
assert.equal(events[0], M1);
const M2 = m.model('Test', Schema({ name: String }), null, { overwriteModels: true });
assert.equal(events.length, 2);
assert.equal(events[1], M2);
const M3 = m.connection.model('Test', Schema({ name: String }), null, { overwriteModels: true });
assert.equal(events.length, 3);
assert.equal(events[2], M3);
assert.ok(M1 !== M2);
assert.ok(M2 !== M3);
assert.throws(() => m.model('Test', Schema({ name: String })), /overwrite/);
});
it('allows setting `overwriteModels` globally (gh-9406)', function() {
const m = new mongoose.Mongoose();