forked from mongodb/node-mongodb-native
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
1908 lines (1718 loc) · 78.3 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
/**
* Module dependencies.
* @ignore
*/
var QueryCommand = require('./commands/query_command').QueryCommand
, DbCommand = require('./commands/db_command').DbCommand
, MongoReply = require('./responses/mongo_reply').MongoReply
, Admin = require('./admin').Admin
, Collection = require('./collection').Collection
, Server = require('./connection/server').Server
, ReplSet = require('./connection/repl_set/repl_set').ReplSet
, ReadPreference = require('./connection/read_preference').ReadPreference
, Mongos = require('./connection/mongos').Mongos
, Cursor = require('./cursor').Cursor
, EventEmitter = require('events').EventEmitter
, inherits = require('util').inherits
, crypto = require('crypto')
, timers = require('timers')
, utils = require('./utils')
, mongodb_cr_authenticate = require('./auth/mongodb_cr.js').authenticate
, mongodb_gssapi_authenticate = require('./auth/mongodb_gssapi.js').authenticate
, mongodb_sspi_authenticate = require('./auth/mongodb_sspi.js').authenticate;
var hasKerberos = false;
// Check if we have a the kerberos library
try {
require('kerberos');
hasKerberos = true;
} catch(err) {
console.dir(err)
}
// Set processor, setImmediate if 0.10 otherwise nextTick
var processor = timers.setImmediate ? timers.setImmediate : process.nextTick;
/**
* Create a new Db instance.
*
* Options
* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
* - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
* - **fsync**, (Boolean, default:false) write waits for fsync before returning
* - **journal**, (Boolean, default:false) write waits for journal sync before returning
* - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* - **native_parser** {Boolean, default:false}, use c++ bson parser.
* - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client.
* - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.
* - **serializeFunctions** {Boolean, default:false}, serialize functions.
* - **raw** {Boolean, default:false}, peform operations using raw bson buffers.
* - **recordQueryStats** {Boolean, default:false}, record query statistics during execution.
* - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries.
* - **numberOfRetries** {Number, default:5}, number of retries off connection.
* - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**.
* - **slaveOk** {Number, default:null}, force setting of SlaveOk flag on queries (only use when explicitly connecting to a secondary server).
*
* Deprecated Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
*
* @class Represents a Db
* @param {String} databaseName name of the database.
* @param {Object} serverConfig server config object.
* @param {Object} [options] additional options for the collection.
*/
function Db(databaseName, serverConfig, options) {
if(!(this instanceof Db)) return new Db(databaseName, serverConfig, options);
EventEmitter.call(this);
var self = this;
this.databaseName = databaseName;
this.serverConfig = serverConfig;
this.options = options == null ? {} : options;
// State to check against if the user force closed db
this._applicationClosed = false;
// Fetch the override flag if any
var overrideUsedFlag = this.options['override_used_flag'] == null ? false : this.options['override_used_flag'];
// Verify that nobody is using this config
if(!overrideUsedFlag && this.serverConfig != null && typeof this.serverConfig == 'object' && this.serverConfig._isUsed && this.serverConfig._isUsed()) {
throw new Error("A Server or ReplSet instance cannot be shared across multiple Db instances");
} else if(!overrideUsedFlag && typeof this.serverConfig == 'object'){
// Set being used
this.serverConfig._used = true;
}
// Allow slaveOk override
this.slaveOk = this.options["slave_ok"] == null ? false : this.options["slave_ok"];
this.slaveOk = this.options["slaveOk"] == null ? this.slaveOk : this.options["slaveOk"];
// Ensure we have a valid db name
validateDatabaseName(databaseName);
// Contains all the connections for the db
try {
this.native_parser = this.options.native_parser;
// The bson lib
var bsonLib = this.bsonLib = this.options.native_parser ? require('bson').BSONNative : require('bson').BSONPure;
// Fetch the serializer object
var BSON = bsonLib.BSON;
// Create a new instance
this.bson = new BSON([bsonLib.Long, bsonLib.ObjectID, bsonLib.Binary, bsonLib.Code, bsonLib.DBRef, bsonLib.Symbol, bsonLib.Double, bsonLib.Timestamp, bsonLib.MaxKey, bsonLib.MinKey]);
// Backward compatibility to access types
this.bson_deserializer = bsonLib;
this.bson_serializer = bsonLib;
} catch (err) {
// If we tried to instantiate the native driver
var msg = "Native bson parser not compiled, please compile "
+ "or avoid using native_parser=true";
throw Error(msg);
}
// Internal state of the server
this._state = 'disconnected';
this.pkFactory = this.options.pk == null ? bsonLib.ObjectID : this.options.pk;
this.forceServerObjectId = this.options.forceServerObjectId != null ? this.options.forceServerObjectId : false;
// Added safe
this.safe = this.options.safe == null ? false : this.options.safe;
// If we have not specified a "safe mode" we just print a warning to the console
if(this.options.safe == null && this.options.w == null && this.options.journal == null && this.options.fsync == null) {
console.log("========================================================================================");
console.log("= Please ensure that you set the default write concern for the database by setting =");
console.log("= one of the options =");
console.log("= =");
console.log("= w: (value of > -1 or the string 'majority'), where < 1 means =");
console.log("= no write acknowlegement =");
console.log("= journal: true/false, wait for flush to journal before acknowlegement =");
console.log("= fsync: true/false, wait for flush to file system before acknowlegement =");
console.log("= =");
console.log("= For backward compatibility safe is still supported and =");
console.log("= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] =");
console.log("= the default value is false which means the driver receives does not =");
console.log("= return the information of the success/error of the insert/update/remove =");
console.log("= =");
console.log("= ex: new Db(new Server('localhost', 27017), {safe:false}) =");
console.log("= =");
console.log("= http://www.mongodb.org/display/DOCS/getLastError+Command =");
console.log("= =");
console.log("= The default of no acknowlegement will change in the very near future =");
console.log("= =");
console.log("= This message will disappear when the default safe is set on the driver Db =");
console.log("========================================================================================");
}
// Internal states variables
this.notReplied ={};
this.isInitializing = true;
this.openCalled = false;
// Command queue, keeps a list of incoming commands that need to be executed once the connection is up
this.commands = [];
// Set up logger
this.logger = this.options.logger != null
&& (typeof this.options.logger.debug == 'function')
&& (typeof this.options.logger.error == 'function')
&& (typeof this.options.logger.log == 'function')
? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}};
// Associate the logger with the server config
this.serverConfig.logger = this.logger;
if(this.serverConfig.strategyInstance) this.serverConfig.strategyInstance.logger = this.logger;
this.tag = new Date().getTime();
// Just keeps list of events we allow
this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[]};
// Controls serialization options
this.serializeFunctions = this.options.serializeFunctions != null ? this.options.serializeFunctions : false;
// Raw mode
this.raw = this.options.raw != null ? this.options.raw : false;
// Record query stats
this.recordQueryStats = this.options.recordQueryStats != null ? this.options.recordQueryStats : false;
// If we have server stats let's make sure the driver objects have it enabled
if(this.recordQueryStats == true) {
this.serverConfig.enableRecordQueryStats(true);
}
// Retry information
this.retryMiliSeconds = this.options.retryMiliSeconds != null ? this.options.retryMiliSeconds : 1000;
this.numberOfRetries = this.options.numberOfRetries != null ? this.options.numberOfRetries : 60;
// Set default read preference if any
this.readPreference = this.options.readPreference;
// Ensure we keep a reference to this db
this.serverConfig._dbStore.add(this);
};
/**
* @ignore
*/
function validateDatabaseName(databaseName) {
if(typeof databaseName !== 'string') throw new Error("database name must be a string");
if(databaseName.length === 0) throw new Error("database name cannot be the empty string");
var invalidChars = [" ", ".", "$", "/", "\\"];
for(var i = 0; i < invalidChars.length; i++) {
if(databaseName.indexOf(invalidChars[i]) != -1) throw new Error("database names cannot contain the character '" + invalidChars[i] + "'");
}
}
/**
* @ignore
*/
inherits(Db, EventEmitter);
/**
* Initialize the database connection.
*
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the index information or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.open = function(callback) {
var self = this;
// Check that the user has not called this twice
if(this.openCalled) {
// Close db
this.close();
// Throw error
throw new Error("db object already connecting, open cannot be called multiple times");
}
// If we have a specified read preference
if(this.readPreference != null) this.serverConfig.setReadPreference(this.readPreference);
// Set that db has been opened
this.openCalled = true;
// Set the status of the server
self._state = 'connecting';
// Set up connections
if(self.serverConfig instanceof Server || self.serverConfig instanceof ReplSet || self.serverConfig instanceof Mongos) {
// Ensure we have the original options passed in for the server config
var connect_options = {};
for(var name in self.serverConfig.options) {
connect_options[name] = self.serverConfig.options[name]
}
connect_options.firstCall = true;
// Attempt to connect
self.serverConfig.connect(self, connect_options, function(err, result) {
if(err != null) {
// Set that db has been closed
self.openCalled = false;
// Return error from connection
return callback(err, null);
}
// Set the status of the server
self._state = 'connected';
// If we have queued up commands execute a command to trigger replays
if(self.commands.length > 0) _execute_queued_command(self);
// Callback
return callback(null, self);
});
} else {
return callback(Error("Server parameter must be of type Server, ReplSet or Mongos"), null);
}
};
/**
* Create a new Db instance sharing the current socket connections.
*
* @param {String} dbName the name of the database we want to use.
* @return {Db} a db instance using the new database.
* @api public
*/
Db.prototype.db = function(dbName) {
// Copy the options and add out internal override of the not shared flag
var options = {};
for(var key in this.options) {
options[key] = this.options[key];
}
// Add override flag
options['override_used_flag'] = true;
// Create a new db instance
var newDbInstance = new Db(dbName, this.serverConfig, options);
// Add the instance to the list of approved db instances
var allServerInstances = this.serverConfig.allServerInstances();
// Add ourselves to all server callback instances
for(var i = 0; i < allServerInstances.length; i++) {
var server = allServerInstances[i];
server.dbInstances.push(newDbInstance);
}
// Return new db object
return newDbInstance;
}
/**
* Close the current db connection, including all the child db instances. Emits close event if no callback is provided.
*
* @param {Boolean} [forceClose] connection can never be reused.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.close = function(forceClose, callback) {
var self = this;
// Ensure we force close all connections
this._applicationClosed = false;
if(typeof forceClose == 'function') {
callback = forceClose;
} else if(typeof forceClose == 'boolean') {
this._applicationClosed = forceClose;
}
this.serverConfig.close(function(err, result) {
// You can reuse the db as everything is shut down
self.openCalled = false;
// If we have a callback call it
if(callback) callback(err, result);
});
};
/**
* Access the Admin database
*
* @param {Function} [callback] returns the results.
* @return {Admin} the admin db object.
* @api public
*/
Db.prototype.admin = function(callback) {
if(callback == null) return new Admin(this);
callback(null, new Admin(this));
};
/**
* Returns a cursor to all the collection information.
*
* @param {String} [collectionName] the collection name we wish to retrieve the information from.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the options or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.collectionsInfo = function(collectionName, callback) {
if(callback == null && typeof collectionName == 'function') { callback = collectionName; collectionName = null; }
// Create selector
var selector = {};
// If we are limiting the access to a specific collection name
if(collectionName != null) selector.name = this.databaseName + "." + collectionName;
// Return Cursor
// callback for backward compatibility
if(callback) {
callback(null, new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector));
} else {
return new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector);
}
};
/**
* Get the list of all collection names for the specified db
*
* Options
* - **namesOnly** {String, default:false}, Return only the full collection namespace.
*
* @param {String} [collectionName] the collection name we wish to filter by.
* @param {Object} [options] additional options during update.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collection names or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.collectionNames = function(collectionName, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 0);
callback = args.pop();
collectionName = args.length ? args.shift() : null;
options = args.length ? args.shift() || {} : {};
// Ensure no breaking behavior
if(collectionName != null && typeof collectionName == 'object') {
options = collectionName;
collectionName = null;
}
// Let's make our own callback to reuse the existing collections info method
self.collectionsInfo(collectionName, function(err, cursor) {
if(err != null) return callback(err, null);
cursor.toArray(function(err, documents) {
if(err != null) return callback(err, null);
// List of result documents that have been filtered
var filtered_documents = documents.filter(function(document) {
return !(document.name.indexOf(self.databaseName) == -1 || document.name.indexOf('$') != -1);
});
// If we are returning only the names
if(options.namesOnly) {
filtered_documents = filtered_documents.map(function(document) { return document.name });
}
// Return filtered items
callback(null, filtered_documents);
});
});
};
/**
* 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');
*
* Options
* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
* - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
* - **fsync**, (Boolean, default:false) write waits for fsync before returning
* - **journal**, (Boolean, default:false) write waits for journal sync before returning
* - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.
* - **raw** {Boolean, default:false}, perform all operations using raw bson objects.
* - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.
* - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* - **strict**, (Boolean, default:false) throws an error if the collection does not exist
*
* Deprecated Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
*
* @param {String} collectionName the collection name we wish to access.
* @param {Object} [options] returns option results.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collection or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.collection = function(collectionName, options, callback) {
var self = this;
if(typeof options === "function") { callback = options; options = {}; }
// Execute safe
if(options && (options.strict)) {
self.collectionNames(collectionName, function(err, collections) {
if(err != null) return callback(err, null);
if(collections.length == 0) {
return callback(new Error("Collection " + collectionName + " does not exist. Currently in safe mode."), null);
} else {
try {
var collection = new Collection(self, collectionName, self.pkFactory, options);
} catch(err) {
return callback(err, null);
}
return callback(null, collection);
}
});
} else {
try {
var collection = new Collection(self, collectionName, self.pkFactory, options);
} catch(err) {
if(callback == null) {
throw err;
} else {
return callback(err, null);
}
}
// If we have no callback return collection object
return callback == null ? collection : callback(null, collection);
}
};
/**
* Fetch all collections for the current db.
*
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collections or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.collections = function(callback) {
var self = this;
// Let's get the collection names
self.collectionNames(function(err, documents) {
if(err != null) return callback(err, null);
var collections = [];
documents.forEach(function(document) {
collections.push(new Collection(self, document.name.replace(self.databaseName + ".", ''), self.pkFactory));
});
// Return the collection objects
callback(null, collections);
});
};
/**
* Evaluate javascript on the server
*
* Options
* - **nolock** {Boolean, default:false}, Tell MongoDB not to block on the evaulation of the javascript.
*
* @param {Code} code javascript to execute on server.
* @param {Object|Array} [parameters] the parameters for the call.
* @param {Object} [options] the options
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from eval or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.eval = function(code, parameters, options, callback) {
// Unpack calls
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
parameters = args.length ? args.shift() : parameters;
options = args.length ? args.shift() || {} : {};
var finalCode = code;
var finalParameters = [];
// If not a code object translate to one
if(!(finalCode instanceof this.bsonLib.Code)) {
finalCode = new this.bsonLib.Code(finalCode);
}
// Ensure the parameters are correct
if(parameters != null && parameters.constructor != Array && typeof parameters !== 'function') {
finalParameters = [parameters];
} else if(parameters != null && parameters.constructor == Array && typeof parameters !== 'function') {
finalParameters = parameters;
}
// Create execution selector
var selector = {'$eval':finalCode, 'args':finalParameters};
// Check if the nolock parameter is passed in
if(options['nolock']) {
selector['nolock'] = options['nolock'];
}
// Set primary read preference
options.readPreference = ReadPreference.PRIMARY;
// Execute the eval
this.collection(DbCommand.SYSTEM_COMMAND_COLLECTION).findOne(selector, options, function(err, result) {
if(err) return callback(err);
if(result && result.ok == 1) {
callback(null, result.retval);
} else if(result) {
callback(new Error("eval failed: " + result.errmsg), null); return;
} else {
callback(err, result);
}
});
};
/**
* Dereference a dbref, against a db
*
* @param {DBRef} dbRef db reference object we wish to resolve.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dereference or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.dereference = function(dbRef, callback) {
var db = this;
// If we have a db reference then let's get the db first
if(dbRef.db != null) db = this.db(dbRef.db);
// Fetch the collection and find the reference
var collection = db.collection(dbRef.namespace);
collection.findOne({'_id':dbRef.oid}, function(err, result) {
callback(err, result);
});
};
/**
* Logout user from server, fire off on all connections and remove all auth info
*
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from logout or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.logout = function(options, callback) {
var self = this;
// Unpack calls
var args = Array.prototype.slice.call(arguments, 0);
callback = args.pop();
options = args.length ? args.shift() || {} : {};
// Number of connections we need to logout from
var numberOfConnections = this.serverConfig.allRawConnections().length;
// Let's generate the logout command object
var logoutCommand = DbCommand.logoutCommand(self, {logout:1}, options);
self._executeQueryCommand(logoutCommand, {onAll:true}, function(err, result) {
// Count down
numberOfConnections = numberOfConnections - 1;
// Work around the case where the number of connections are 0
if(numberOfConnections <= 0 && typeof callback == 'function') {
var internalCallback = callback;
callback = null;
// Remove the db from auths
self.serverConfig.auth.remove(self.databaseName);
// Handle any errors
if(err == null && result.documents[0].ok == 1) {
internalCallback(null, true);
} else {
err != null ? internalCallback(err, false) : internalCallback(new Error(result.documents[0].errmsg), false);
}
}
});
}
/**
* Authenticate a user against the server.
* authMechanism
* Options
* - **authSource** {String}, The database that the credentials are for,
* different from the name of the current DB, for example admin
* - **authMechanism** {String, default:MONGODB-CR}, The authentication mechanism to use, GSSAPI or MONGODB-CR
*
* @param {String} username username.
* @param {String} password password.
* @param {Object} [options] the options
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from authentication or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.authenticate = function(username, password, options, callback) {
var self = this;
if(typeof callback === 'undefined') {
callback = options;
options = {};
}
// Set default mechanism
if(!options.authMechanism) {
options.authMechanism = 'MONGODB-CR';
} else if(options.authMechanism != 'GSSAPI' && options.authMechanism != 'MONGODB-CR') {
return callback(new Error("only GSSAPI or MONGODB-CR is supported by authMechanism"));
}
// the default db to authenticate against is 'this'
// if authententicate is called from a retry context, it may be another one, like admin
var authdb = options.authdb ? options.authdb : self.databaseName;
authdb = options.authSource ? options.authSource : authdb;
// If classic auth delegate to auth command
if(options.authMechanism == 'MONGODB-CR') {
mongodb_cr_authenticate(self, username, password, authdb, options, callback);
} else if(options.authMechanism == 'GSSAPI') {
//
// Kerberos library is not installed, throw and error
if(hasKerberos == false) {
console.log("========================================================================================");
console.log("= Please make sure that you install the Kerberos library to use GSSAPI =");
console.log("= =");
console.log("= npm install -g kerberos =");
console.log("= =");
console.log("= The Kerberos package is not installed by default for simplicities sake =");
console.log("= and needs to be global install =");
console.log("========================================================================================");
throw new Error("Kerberos library not installed");
}
if(process.platform == 'win32') {
mongodb_sspi_authenticate(self, username, password, authdb, options, callback);
} else {
// We have the kerberos library, execute auth process
mongodb_gssapi_authenticate(self, username, password, authdb, options, callback);
}
}
};
/**
* Add a user to the database.
*
* Options
* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
* - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
* - **fsync**, (Boolean, default:false) write waits for fsync before returning
* - **journal**, (Boolean, default:false) write waits for journal sync before returning
*
* Deprecated Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
*
* @param {String} username username.
* @param {String} password password.
* @param {Object} [options] additional options during update.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from addUser or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.addUser = function(username, password, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 2);
callback = args.pop();
options = args.length ? args.shift() || {} : {};
// Get the error options
var errorOptions = _getWriteConcern(this, options, callback);
errorOptions.w = errorOptions.w == null ? 1 : errorOptions.w;
// Use node md5 generator
var md5 = crypto.createHash('md5');
// Generate keys used for authentication
md5.update(username + ":mongo:" + password);
var userPassword = md5.digest('hex');
// Fetch a user collection
var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION);
// Check if we are inserting the first user
collection.count({}, function(err, count) {
// We got an error (f.ex not authorized)
if(err != null) return callback(err, null);
// Check if the user exists and update i
collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) {
// We got an error (f.ex not authorized)
if(err != null) return callback(err, null);
// Add command keys
var commandOptions = errorOptions;
commandOptions.dbName = options['dbName'];
commandOptions.upsert = true;
// We have a user, let's update the password or upsert if not
collection.update({user: username},{$set: {user: username, pwd: userPassword}}, commandOptions, function(err, results) {
if(count == 0 && err) {
callback(null, [{user:username, pwd:userPassword}]);
} else if(err) {
callback(err, null)
} else {
callback(null, [{user:username, pwd:userPassword}]);
}
});
});
});
};
/**
* Remove a user from a database
*
* Options
* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
* - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
* - **fsync**, (Boolean, default:false) write waits for fsync before returning
* - **journal**, (Boolean, default:false) write waits for journal sync before returning
*
* Deprecated Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
*
* @param {String} username username.
* @param {Object} [options] additional options during update.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.removeUser = function(username, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
options = args.length ? args.shift() || {} : {};
// Figure out the safe mode settings
var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe;
// Override with options passed in if applicable
safe = options != null && options['safe'] != null ? options['safe'] : safe;
// Ensure it's at least set to safe
safe = safe == null ? {w: 1} : safe;
// Fetch a user collection
var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION);
collection.findOne({user: username}, {dbName: options['dbName']}, function(err, user) {
if(user != null) {
// Add command keys
var commandOptions = safe;
commandOptions.dbName = options['dbName'];
collection.remove({user: username}, commandOptions, function(err, result) {
callback(err, true);
});
} else {
callback(err, false);
}
});
};
/**
* Creates a collection on a server pre-allocating space, need to create f.ex capped collections.
*
* Options
* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write
* - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option)
* - **fsync**, (Boolean, default:false) write waits for fsync before returning
* - **journal**, (Boolean, default:false) write waits for journal sync before returning
* - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.
* - **raw** {Boolean, default:false}, perform all operations using raw bson objects.
* - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation.
* - **capped** {Boolean, default:false}, create a capped collection.
* - **size** {Number}, the size of the capped collection in bytes.
* - **max** {Number}, the maximum number of documents in the capped collection.
* - **autoIndexId** {Boolean, default: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.
* - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* - **strict**, (Boolean, default:false) throws an error if collection already exists
*
* Deprecated Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
*
* @param {String} collectionName the collection name we wish to access.
* @param {Object} [options] returns option results.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from createCollection or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.createCollection = function(collectionName, options, callback) {
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
options = args.length ? args.shift() : null;
var self = this;
// Figure out the safe mode settings
var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe;
// Override with options passed in if applicable
safe = options != null && options['safe'] != null ? options['safe'] : safe;
// Ensure it's at least set to safe
safe = safe == null ? {w: 1} : safe;
// Check if we have the name
this.collectionNames(collectionName, function(err, collections) {
if(err != null) return callback(err, null);
var found = false;
collections.forEach(function(collection) {
if(collection.name == self.databaseName + "." + collectionName) found = true;
});
// If the collection exists either throw an exception (if db in safe mode) or return the existing collection
if(found && options && options.strict) {
return callback(new Error("Collection " + collectionName + " already exists. Currently in safe mode."), null);
} else if(found){
try {
var collection = new Collection(self, collectionName, self.pkFactory, options);
} catch(err) {
return callback(err, null);
}
return callback(null, collection);
}
// Create a new collection and return it
self._executeQueryCommand(DbCommand.createCreateCollectionCommand(self, collectionName, options), {read:false, safe:safe}, function(err, result) {
var document = result.documents[0];
// If we have no error let's return the collection
if(err == null && document.ok == 1) {
try {
var collection = new Collection(self, collectionName, self.pkFactory, options);
} catch(err) {
return callback(err, null);
}
return callback(null, collection);
} else {
if (null == err) err = utils.toError(document);
callback(err, null);
}
});
});
};
/**
* Execute a command hash against MongoDB. This lets you acess any commands not available through the api on the server.
*
* @param {Object} selector the command hash to send to the server, ex: {ping:1}.
* @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter.
* @return {null}
* @api public
*/
Db.prototype.command = function(selector, options, callback) {
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
options = args.length ? args.shift() || {} : {};
// Set up the options
var cursor = new Cursor(this
, new Collection(this, DbCommand.SYSTEM_COMMAND_COLLECTION), selector, {}, {
limit: -1, timeout: QueryCommand.OPTS_NO_CURSOR_TIMEOUT, dbName: options['dbName']
});
// Set read preference if we set one
var readPreference = options['readPreference'] ? options['readPreference'] : false;
// Ensure only commands who support read Prefrences are exeuted otherwise override and use Primary
if(readPreference != false) {
if(selector['group'] || selector['aggregate'] || selector['collStats'] || selector['dbStats']
|| selector['count'] || selector['distinct'] || selector['geoNear'] || selector['geoSearch'] || selector['geoWalk']
|| (selector['mapreduce'] && selector.out == 'inline')) {
// Set the read preference
cursor.setReadPreference(readPreference);
} else {
cursor.setReadPreference(ReadPreference.PRIMARY);
}
}
// Return the next object
cursor.nextObject(callback);
};
/**
* Drop a collection from the database, removing it permanently. New accesses will create a new collection.
*
* @param {String} collectionName the name of the collection we wish to drop.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dropCollection or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.dropCollection = function(collectionName, callback) {
var self = this;
callback || (callback = function(){});
// Drop the collection
this._executeQueryCommand(DbCommand.createDropCollectionCommand(this, collectionName), function(err, result) {
if(err == null && result.documents[0].ok == 1) {
return callback(null, true);
}
if(null == err) err = utils.toError(result.documents[0]);
callback(err, null);
});
};
/**
* Rename a collection.
*
* Options
* - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists.
*
* @param {String} fromCollection the name of the current collection we wish to rename.
* @param {String} toCollection the new name of the collection.
* @param {Object} [options] returns option results.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from renameCollection or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {
var self = this;
if(typeof options == 'function') {
callback = options;
options = {}
}
callback || (callback = function(){});
// Execute the command, return the new renamed collection if successful
this._executeQueryCommand(DbCommand.createRenameCollectionCommand(this, fromCollection, toCollection, options), function(err, result) {
if(err == null && result.documents[0].ok == 1) {
return callback(null, new Collection(self, toCollection, self.pkFactory));
}
if(null == err) err = utils.toError(result.documents[0]);
callback(err, null);
});
};
/**
* Return last error message for the given connection, note options can be combined.
*
* Options
* - **fsync** {Boolean, default:false}, option forces the database to fsync all files before returning.
* - **j** {Boolean, default:false}, awaits the journal commit before returning, > MongoDB 2.0.
* - **w** {Number}, until a write operation has been replicated to N servers.
* - **wtimeout** {Number}, number of miliseconds to wait before timing out.
*
* Connection Options
* - **connection** {Connection}, fire the getLastError down a specific connection.
*
* @param {Object} [options] returns option results.
* @param {Object} [connectionOptions] returns option results.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from lastError or null if an error occured.
* @return {null}
* @api public
*/
Db.prototype.lastError = function(options, connectionOptions, callback) {
// Unpack calls
var args = Array.prototype.slice.call(arguments, 0);
callback = args.pop();
options = args.length ? args.shift() || {} : {};
connectionOptions = args.length ? args.shift() || {} : {};
this._executeQueryCommand(DbCommand.createGetLastErrorCommand(options, this), connectionOptions, function(err, error) {
callback(err, error && error.documents);
});
};
/**
* Legacy method calls.
*
* @ignore
* @api private
*/
Db.prototype.error = Db.prototype.lastError;
Db.prototype.lastStatus = Db.prototype.lastError;
/**
* Return all errors up to the last time db reset_error_history was called.
*
* Options
* - **connection** {Connection}, fire the getLastError down a specific connection.
*
* @param {Object} [options] returns option results.
* @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from previousErrors or null if an error occured.
* @return {null}
* @api public
*/