-
Notifications
You must be signed in to change notification settings - Fork 683
/
db.js
1810 lines (1593 loc) · 66.6 KB
/
db.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';
var EventEmitter = require('events').EventEmitter,
inherits = require('util').inherits,
getSingleProperty = require('./utils').getSingleProperty,
shallowClone = require('./utils').shallowClone,
parseIndexOptions = require('./utils').parseIndexOptions,
debugOptions = require('./utils').debugOptions,
CommandCursor = require('./command_cursor'),
handleCallback = require('./utils').handleCallback,
filterOptions = require('./utils').filterOptions,
toError = require('./utils').toError,
ReadPreference = require('mongodb-core').ReadPreference,
f = require('util').format,
Admin = require('./admin'),
Code = require('mongodb-core').BSON.Code,
MongoError = require('mongodb-core').MongoError,
ObjectID = require('mongodb-core').ObjectID,
Define = require('./metadata'),
Logger = require('mongodb-core').Logger,
Collection = require('./collection'),
crypto = require('crypto'),
mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern,
executeOperation = require('./utils').executeOperation;
var debugFields = [
'authSource',
'w',
'wtimeout',
'j',
'native_parser',
'forceServerObjectId',
'serializeFunctions',
'raw',
'promoteLongs',
'promoteValues',
'promoteBuffers',
'bufferMaxEntries',
'numberOfRetries',
'retryMiliSeconds',
'readPreference',
'pkFactory',
'parentDb',
'promiseLibrary',
'noListener'
];
// Filter out any write concern options
var illegalCommandFields = [
'w',
'wtimeout',
'j',
'fsync',
'autoIndexId',
'strict',
'serializeFunctions',
'pkFactory',
'raw',
'readPreference',
'session'
];
/**
* @fileOverview The **Db** class is a class that represents a MongoDB Database.
*
* @example
* const MongoClient = require('mongodb').MongoClient;
* const test = require('assert');
* // Connection url
* const url = 'mongodb://localhost:27017';
* // Database Name
* const dbName = 'test';
* // Connect using MongoClient
* MongoClient.connect(url, function(err, client) {
* // Get an additional db
* const testDb = client.db('test');
* client.close();
* });
*/
// Allowed parameters
var legalOptionNames = [
'w',
'wtimeout',
'fsync',
'j',
'readPreference',
'readPreferenceTags',
'native_parser',
'forceServerObjectId',
'pkFactory',
'serializeFunctions',
'raw',
'bufferMaxEntries',
'authSource',
'ignoreUndefined',
'promoteLongs',
'promiseLibrary',
'readConcern',
'retryMiliSeconds',
'numberOfRetries',
'parentDb',
'noListener',
'loggerLevel',
'logger',
'promoteBuffers',
'promoteLongs',
'promoteValues',
'compression',
'retryWrites'
];
/**
* Creates a new Db instance
* @class
* @param {string} databaseName The name of the database this instance represents.
* @param {(Server|ReplSet|Mongos)} topology The server topology for the database.
* @param {object} [options=null] Optional settings.
* @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
* @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
* @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
* @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
* @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
* @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
* @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
* @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
* @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology.
* @property {number} bufferMaxEntries Current bufferMaxEntries value for the database
* @property {string} databaseName The name of the database this instance represents.
* @property {object} options The options associated with the db instance.
* @property {boolean} native_parser The current value of the parameter native_parser.
* @property {boolean} slaveOk The current slaveOk value for the db instance.
* @property {object} writeConcern The current write concern values.
* @property {object} topology Access the topology object (single server, replicaset or mongos).
* @fires Db#close
* @fires Db#reconnect
* @fires Db#error
* @fires Db#timeout
* @fires Db#parseError
* @fires Db#fullsetup
* @return {Db} a Db instance.
*/
var Db = function(databaseName, topology, options) {
options = options || {};
if (!(this instanceof Db)) return new Db(databaseName, topology, options);
EventEmitter.call(this);
var self = this;
// Get the promiseLibrary
var promiseLibrary = options.promiseLibrary || Promise;
// Filter the options
options = filterOptions(options, legalOptionNames);
// Ensure we put the promiseLib in the options
options.promiseLibrary = promiseLibrary;
// var self = this; // Internal state of the db object
this.s = {
// Database name
databaseName: databaseName,
// DbCache
dbCache: {},
// Children db's
children: [],
// Topology
topology: topology,
// Options
options: options,
// Logger instance
logger: Logger('Db', options),
// Get the bson parser
bson: topology ? topology.bson : null,
// Unpack read preference
readPreference: options.readPreference,
// Set buffermaxEntries
bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1,
// Parent db (if chained)
parentDb: options.parentDb || null,
// Set up the primary key factory or fallback to ObjectID
pkFactory: options.pkFactory || ObjectID,
// Get native parser
nativeParser: options.nativeParser || options.native_parser,
// Promise library
promiseLibrary: promiseLibrary,
// No listener
noListener: typeof options.noListener === 'boolean' ? options.noListener : false,
// ReadConcern
readConcern: options.readConcern
};
// Ensure we have a valid db name
validateDatabaseName(self.s.databaseName);
// Add a read Only property
getSingleProperty(this, 'serverConfig', self.s.topology);
getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries);
getSingleProperty(this, 'databaseName', self.s.databaseName);
// This is a child db, do not register any listeners
if (options.parentDb) return;
if (this.s.noListener) return;
// Add listeners
topology.on('error', createListener(self, 'error', self));
topology.on('timeout', createListener(self, 'timeout', self));
topology.on('close', createListener(self, 'close', self));
topology.on('parseError', createListener(self, 'parseError', self));
topology.once('open', createListener(self, 'open', self));
topology.once('fullsetup', createListener(self, 'fullsetup', self));
topology.once('all', createListener(self, 'all', self));
topology.on('reconnect', createListener(self, 'reconnect', self));
};
inherits(Db, EventEmitter);
var define = (Db.define = new Define('Db', Db, false));
// Topology
Object.defineProperty(Db.prototype, 'topology', {
enumerable: true,
get: function() {
return this.s.topology;
}
});
// Options
Object.defineProperty(Db.prototype, 'options', {
enumerable: true,
get: function() {
return this.s.options;
}
});
// slaveOk specified
Object.defineProperty(Db.prototype, 'slaveOk', {
enumerable: true,
get: function() {
if (
this.s.options.readPreference != null &&
(this.s.options.readPreference !== 'primary' ||
this.s.options.readPreference.mode !== 'primary')
) {
return true;
}
return false;
}
});
// get the write Concern
Object.defineProperty(Db.prototype, 'writeConcern', {
enumerable: true,
get: function() {
var ops = {};
if (this.s.options.w != null) ops.w = this.s.options.w;
if (this.s.options.j != null) ops.j = this.s.options.j;
if (this.s.options.fsync != null) ops.fsync = this.s.options.fsync;
if (this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout;
return ops;
}
});
/**
* Ensures provided read preference is properly converted into an object
* @param {(ReadPreference|string|object)} readPreference the user provided read preference
* @return {ReadPreference}
*/
const convertReadPreference = function(readPreference) {
if (readPreference) {
if (typeof readPreference === 'string') {
return new ReadPreference(readPreference);
} else if (
readPreference &&
!(readPreference instanceof ReadPreference) &&
typeof readPreference === 'object'
) {
const mode = readPreference.mode || readPreference.preference;
if (mode && typeof mode === 'string') {
return new ReadPreference(mode, readPreference.tags, {
maxStalenessSeconds: readPreference.maxStalenessSeconds
});
}
} else if (!(readPreference instanceof ReadPreference)) {
throw new TypeError('Invalid read preference: ' + readPreference);
}
}
return readPreference;
};
/**
* The callback format for results
* @callback Db~resultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {object} result The result object if the command was executed successfully.
*/
var executeCommand = function(self, command, options, callback) {
// Did the user destroy the topology
if (self.serverConfig && self.serverConfig.isDestroyed())
return callback(new MongoError('topology was destroyed'));
// Get the db name we are executing against
var dbName = options.dbName || options.authdb || self.s.databaseName;
// If we have a readPreference set
if (options.readPreference == null && self.s.readPreference) {
options.readPreference = self.s.readPreference;
}
// Convert the readPreference if its not a write
if (options.readPreference) {
options.readPreference = convertReadPreference(options.readPreference);
} else {
options.readPreference = ReadPreference.primary;
}
// Debug information
if (self.s.logger.isDebug())
self.s.logger.debug(
f(
'executing command %s against %s with options [%s]',
JSON.stringify(command),
f('%s.$cmd', dbName),
JSON.stringify(debugOptions(debugFields, options))
)
);
// Execute command
self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) {
if (err) return handleCallback(callback, err);
if (options.full) return handleCallback(callback, null, result);
handleCallback(callback, null, result.result);
});
};
/**
* Execute a command
* @method
* @param {object} command The command hash
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.command = function(command, options, callback) {
// Change the callback
if (typeof options === 'function') (callback = options), (options = {});
// Clone the options
options = shallowClone(options);
return executeOperation(this.s.topology, executeCommand, [this, command, options, callback]);
};
define.classMethod('command', { callback: true, promise: true });
/**
* Return the Admin db instance
* @method
* @return {Admin} return the new Admin db instance
*/
Db.prototype.admin = function() {
return new Admin(this, this.s.topology, this.s.promiseLibrary);
};
define.classMethod('admin', { callback: false, promise: false, returns: [Admin] });
/**
* The callback format for the collection method, must be used if strict is specified
* @callback Db~collectionResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Collection} collection The collection instance.
*/
var collectionKeys = [
'pkFactory',
'readPreference',
'serializeFunctions',
'strict',
'readConcern',
'ignoreUndefined',
'promoteValues',
'promoteBuffers',
'promoteLongs'
];
/**
* Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can
* can use it without a callback in the following way: `var collection = db.collection('mycollection');`
*
* @method
* @param {string} name the collection name we wish to access.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
* @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
* @param {boolean} [options.strict=false] Returns an error if the collection does not exist
* @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
* @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
* @param {Db~collectionResultCallback} callback The collection result callback
* @return {Collection} return the new Collection instance if not in strict mode
*/
Db.prototype.collection = function(name, options, callback) {
var self = this;
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
options = shallowClone(options);
// Set the promise library
options.promiseLibrary = this.s.promiseLibrary;
// If we have not set a collection level readConcern set the db level one
options.readConcern = options.readConcern || this.s.readConcern;
// Do we have ignoreUndefined set
if (this.s.options.ignoreUndefined) {
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
// Merge in all needed options and ensure correct writeConcern merging from db level
options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true);
// Execute
if (options == null || !options.strict) {
try {
var collection = new Collection(
this,
this.s.topology,
this.s.databaseName,
name,
this.s.pkFactory,
options
);
if (callback) callback(null, collection);
return collection;
} catch (err) {
// if(err instanceof MongoError && callback) return callback(err);
if (callback) return callback(err);
throw err;
}
}
// Strict mode
if (typeof callback !== 'function') {
throw toError(f('A callback is required in strict mode. While getting collection %s.', name));
}
// Did the user destroy the topology
if (self.serverConfig && self.serverConfig.isDestroyed()) {
return callback(new MongoError('topology was destroyed'));
}
// Strict mode
this.listCollections({ name: name }, options).toArray(function(err, collections) {
if (err != null) return handleCallback(callback, err, null);
if (collections.length === 0)
return handleCallback(
callback,
toError(f('Collection %s does not exist. Currently in strict mode.', name)),
null
);
try {
return handleCallback(
callback,
null,
new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)
);
} catch (err) {
return handleCallback(callback, err, null);
}
});
};
define.classMethod('collection', { callback: true, promise: false, returns: [Collection] });
function decorateWithWriteConcern(command, self, options) {
// Do we support write concerns 3.4 and higher
if (self.s.topology.capabilities().commandsTakeWriteConcern) {
// Get the write concern settings
var finalOptions = writeConcern(shallowClone(options), self, options);
// Add the write concern to the command
if (finalOptions.writeConcern) {
command.writeConcern = finalOptions.writeConcern;
}
}
}
var createCollection = function(self, name, options, callback) {
// Get the write concern options
var finalOptions = writeConcern(shallowClone(options), self, options);
// Did the user destroy the topology
if (self.serverConfig && self.serverConfig.isDestroyed()) {
return callback(new MongoError('topology was destroyed'));
}
// Check if we have the name
self
.listCollections({ name: name }, finalOptions)
.setReadPreference(ReadPreference.PRIMARY)
.toArray(function(err, collections) {
if (err != null) return handleCallback(callback, err, null);
if (collections.length > 0 && finalOptions.strict) {
return handleCallback(
callback,
MongoError.create({
message: f('Collection %s already exists. Currently in strict mode.', name),
driver: true
}),
null
);
} else if (collections.length > 0) {
try {
return handleCallback(
callback,
null,
new Collection(
self,
self.s.topology,
self.s.databaseName,
name,
self.s.pkFactory,
options
)
);
} catch (err) {
return handleCallback(callback, err);
}
}
// Create collection command
var cmd = { create: name };
// Decorate command with writeConcern if supported
decorateWithWriteConcern(cmd, self, options);
// Add all optional parameters
for (var n in options) {
if (
options[n] != null &&
typeof options[n] !== 'function' &&
illegalCommandFields.indexOf(n) === -1
) {
cmd[n] = options[n];
}
}
// Force a primary read Preference
finalOptions.readPreference = ReadPreference.PRIMARY;
// Execute command
self.command(cmd, finalOptions, function(err) {
if (err) return handleCallback(callback, err);
handleCallback(
callback,
null,
new Collection(
self,
self.s.topology,
self.s.databaseName,
name,
self.s.pkFactory,
options
)
);
});
});
};
/**
* Create a new collection on a server with the specified options. Use this to create capped collections.
* More information about command options available at https://docs.mongodb.com/manual/reference/command/create/
*
* @method
* @param {string} name the collection name we wish to access.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
* @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
* @param {boolean} [options.strict=false] Returns an error if the collection does not exist
* @param {boolean} [options.capped=false] Create a capped collection.
* @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2.
* @param {number} [options.size=null] The size of the capped collection in bytes.
* @param {number} [options.max=null] The maximum number of documents in the capped collection.
* @param {number} [options.flags=null] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag.
* @param {object} [options.storageEngine=null] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher.
* @param {object} [options.validator=null] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher.
* @param {string} [options.validationLevel=null] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher.
* @param {string} [options.validationAction=null] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher.
* @param {object} [options.indexOptionDefaults=null] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher.
* @param {string} [options.viewOn=null] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher.
* @param {array} [options.pipeline=null] An array that consists of the aggregation pipeline stage. create creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher.
* @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Db~collectionResultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.createCollection = function(name, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary;
return executeOperation(this.s.topology, createCollection, [this, name, options, callback]);
};
define.classMethod('createCollection', { callback: true, promise: true });
/**
* Get all the db statistics.
*
* @method
* @param {object} [options=null] Optional settings.
* @param {number} [options.scale=null] Divide the returned sizes by scale value.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Db~resultCallback} [callback] The collection result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.stats = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Build command object
var commandObject = { dbStats: true };
// Check if we have the scale value
if (options['scale'] != null) commandObject['scale'] = options['scale'];
// If we have a readPreference set
if (options.readPreference == null && this.s.readPreference) {
options.readPreference = this.s.readPreference;
}
// Execute the command
return this.command(commandObject, options, callback);
};
define.classMethod('stats', { callback: true, promise: true });
// Transformation methods for cursor results
var listCollectionsTranforms = function(databaseName) {
var matching = f('%s.', databaseName);
return {
doc: function(doc) {
var index = doc.name.indexOf(matching);
// Remove database name if available
if (doc.name && index === 0) {
doc.name = doc.name.substr(index + matching.length);
}
return doc;
}
};
};
/**
* Get the list of all collection information for the specified db.
*
* @method
* @param {object} [filter={}] Query to filter collections by
* @param {object} [options=null] Optional settings.
* @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {ClientSession} [options.session] optional session to use for this operation
* @return {CommandCursor}
*/
Db.prototype.listCollections = function(filter, options) {
filter = filter || {};
options = options || {};
// Shallow clone the object
options = shallowClone(options);
// Set the promise library
options.promiseLibrary = this.s.promiseLibrary;
// Ensure valid readPreference
if (options.readPreference) {
options.readPreference = convertReadPreference(options.readPreference);
} else {
options.readPreference = this.s.readPreference || ReadPreference.primary;
}
// We have a list collections command
if (this.serverConfig.capabilities().hasListCollectionsCommand) {
// Cursor options
var cursor = options.batchSize ? { batchSize: options.batchSize } : {};
// Build the command
var command = { listCollections: true, filter: filter, cursor: cursor };
// Set the AggregationCursor constructor
options.cursorFactory = CommandCursor;
// Create the cursor
cursor = this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options);
// Do we have a readPreference, apply it
if (options.readPreference) {
cursor.setReadPreference(options.readPreference);
}
// Return the cursor
return cursor;
}
// We cannot use the listCollectionsCommand
if (!this.serverConfig.capabilities().hasListCollectionsCommand) {
// If we have legacy mode and have not provided a full db name filter it
if (
typeof filter.name === 'string' &&
!new RegExp('^' + this.databaseName + '\\.').test(filter.name)
) {
filter = shallowClone(filter);
filter.name = f('%s.%s', this.s.databaseName, filter.name);
}
}
// No filter, filter by current database
if (filter == null) {
filter.name = f('/%s/', this.s.databaseName);
}
// Rewrite the filter to use $and to filter out indexes
if (filter.name) {
filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] };
} else {
filter = { name: /^((?!\$).)*$/ };
}
// Return options
var _options = { transforms: listCollectionsTranforms(this.s.databaseName) };
// Get the cursor
cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options);
// Do we have a readPreference, apply it
if (options.readPreference) cursor.setReadPreference(options.readPreference);
// Set the passed in batch size if one was provided
if (options.batchSize) cursor = cursor.batchSize(options.batchSize);
// We have a fallback mode using legacy systems collections
return cursor;
};
define.classMethod('listCollections', {
callback: false,
promise: false,
returns: [CommandCursor]
});
var evaluate = function(self, code, parameters, options, callback) {
var finalCode = code;
var finalParameters = [];
// Did the user destroy the topology
if (self.serverConfig && self.serverConfig.isDestroyed())
return callback(new MongoError('topology was destroyed'));
// If not a code object translate to one
if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode);
// Ensure the parameters are correct
if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') {
finalParameters = [parameters];
} else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') {
finalParameters = parameters;
}
// Create execution selector
var cmd = { $eval: finalCode, args: finalParameters };
// Check if the nolock parameter is passed in
if (options['nolock']) {
cmd['nolock'] = options['nolock'];
}
// Set primary read preference
options.readPreference = new ReadPreference(ReadPreference.PRIMARY);
// Execute the command
self.command(cmd, options, function(err, result) {
if (err) return handleCallback(callback, err, null);
if (result && result.ok === 1) return handleCallback(callback, null, result.retval);
if (result)
return handleCallback(
callback,
MongoError.create({ message: f('eval failed: %s', result.errmsg), driver: true }),
null
);
handleCallback(callback, err, result);
});
};
/**
* Evaluate JavaScript on the server
*
* @method
* @param {Code} code JavaScript to execute on server.
* @param {(object|array)} parameters The parameters for the call.
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Db~resultCallback} [callback] The results callback
* @deprecated Eval is deprecated on MongoDB 3.2 and forward
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.eval = function(code, parameters, options, callback) {
var args = Array.prototype.slice.call(arguments, 1);
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;
parameters = args.length ? args.shift() : parameters;
options = args.length ? args.shift() || {} : {};
return executeOperation(this.s.topology, evaluate, [this, code, parameters, options, callback]);
};
define.classMethod('eval', { callback: true, promise: true });
/**
* Rename a collection.
*
* @method
* @param {string} fromCollection Name of current collection to rename.
* @param {string} toCollection New name of of the collection.
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Db~collectionResultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Add return new collection
options.new_collection = true;
const collection = this.collection(fromCollection);
return executeOperation(this.s.topology, collection.rename.bind(collection), [
toCollection,
options,
callback
]);
};
define.classMethod('renameCollection', { callback: true, promise: true });
/**
* Drop a collection from the database, removing it permanently. New accesses will create a new collection.
*
* @method
* @param {string} name Name of collection to drop
* @param {Object} [options] Optional settings
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Db~resultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.dropCollection = function(name, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Command to execute
var cmd = { drop: name };
// Decorate with write concern
decorateWithWriteConcern(cmd, this, options);
// options
const opts = Object.assign({}, this.s.options, { readPreference: ReadPreference.PRIMARY });
if (options.session) opts.session = options.session;
return executeOperation(this.s.topology, dropCollection, [this, cmd, opts, callback]);
};
const dropCollection = (self, cmd, options, callback) => {
return self.command(cmd, options, function(err, result) {
// Did the user destroy the topology
if (self.serverConfig && self.serverConfig.isDestroyed()) {
return callback(new MongoError('topology was destroyed'));
}
if (err) return handleCallback(callback, err);
if (result.ok) return handleCallback(callback, null, true);
handleCallback(callback, null, false);
});
};
define.classMethod('dropCollection', { callback: true, promise: true });
/**
* Drop a database, removing it permanently from the server.
*
* @method
* @param {Object} [options] Optional settings
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Db~resultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.dropDatabase = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Drop database command
var cmd = { dropDatabase: 1 };
// Decorate with write concern
decorateWithWriteConcern(cmd, this, options);
// Ensure primary only
const finalOptions = Object.assign(
{},
{ readPreference: ReadPreference.PRIMARY },
this.s.options
);
if (options.session) {
finalOptions.session = options.session;
}
return executeOperation(this.s.topology, dropDatabase, [this, cmd, finalOptions, callback]);
};
const dropDatabase = (self, cmd, options, callback) => {
self.command(cmd, options, function(err, result) {
// Did the user destroy the topology
if (self.serverConfig && self.serverConfig.isDestroyed()) {
return callback(new MongoError('topology was destroyed'));
}
if (callback == null) return;
if (err) return handleCallback(callback, err, null);
handleCallback(callback, null, result.ok ? true : false);
});
};
define.classMethod('dropDatabase', { callback: true, promise: true });
/**
* Fetch all collections for the current db.
*
* @method
* @param {Object} [options] Optional settings
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Db~collectionsResultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.collections = function(options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
return executeOperation(this.s.topology, collections, [this, options, callback]);
};
var collections = function(self, options, callback) {
// Let's get the collection names
self.listCollections({}, options).toArray(function(err, documents) {
if (err != null) return handleCallback(callback, err, null);
// Filter collections removing any illegal ones
documents = documents.filter(function(doc) {
return doc.name.indexOf('$') === -1;
});
// Return the collection objects
handleCallback(
callback,
null,
documents.map(function(d) {
return new Collection(
self,
self.s.topology,
self.s.databaseName,
d.name,
self.s.pkFactory,
self.s.options
);
})
);
});
};
define.classMethod('collections', { callback: true, promise: true });
/**
* Runs a command on the database as admin.
* @method
* @param {object} command The command hash
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {ClientSession} [options.session] optional session to use for this operation
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.executeDbAdminCommand = function(selector, options, callback) {
if (typeof options === 'function') (callback = options), (options = {});
options = options || {};
// Convert read preference
if (options.readPreference) {
options.readPreference = convertReadPreference(options.readPreference);
}
return executeOperation(this.s.topology, executeDbAdminCommand, [