forked from mongodb/node-mongodb-native
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathcollection.js
1508 lines (1336 loc) · 53.1 KB
/
collection.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 InsertCommand = require('./commands/insert_command').InsertCommand
, QueryCommand = require('./commands/query_command').QueryCommand
, DeleteCommand = require('./commands/delete_command').DeleteCommand
, UpdateCommand = require('./commands/update_command').UpdateCommand
, DbCommand = require('./commands/db_command').DbCommand
, ObjectID = require('bson').ObjectID
, Code = require('bson').Code
, Cursor = require('./cursor').Cursor
, utils = require('./utils');
/**
* Precompiled regexes
* @ignore
**/
const eErrorMessages = /No matching object found/;
/**
* toString helper.
* @ignore
*/
var toString = Object.prototype.toString;
/**
* Create a new Collection instance
*
* Options
* - **slaveOk** {Boolean, default:false}, Allow reads from secondaries.
* - **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.
*
* @class Represents a Collection
* @param {Object} db db instance.
* @param {String} collectionName collection name.
* @param {Object} [pkFactory] alternative primary key factory.
* @param {Object} [options] additional options for the collection.
* @return {Object} a collection instance.
*/
function Collection (db, collectionName, pkFactory, options) {
if(!(this instanceof Collection)) return new Collection(db, collectionName, pkFactory, options);
checkCollectionName(collectionName);
this.db = db;
this.collectionName = collectionName;
this.internalHint = null;
this.opts = options != null && ('object' === typeof options) ? options : {};
this.slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk;
this.serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions;
this.raw = options == null || options.raw == null ? db.raw : options.raw;
this.pkFactory = pkFactory == null
? ObjectID
: pkFactory;
var self = this;
Object.defineProperty(this, "hint", {
enumerable: true
, get: function () {
return this.internalHint;
}
, set: function (v) {
this.internalHint = normalizeHintField(v);
}
});
}
/**
* Inserts a single document or a an array of documents into MongoDB.
*
* Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
* - **keepGoing** {Boolean, default:false}, keep inserting documents even if one document has an error, *mongodb 1.9.1 >*.
* - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.
*
* @param {Array|Object} docs
* @param {Object} [options] optional options for insert command
* @param {Function} [callback] optional callback for the function, must be provided when using `safe` or `strict` mode
* @return {null}
* @api public
*/
Collection.prototype.insert = function insert (docs, options, callback) {
if ('function' === typeof options) callback = options, options = {};
if(options == null) options = {};
if(!('function' === typeof callback)) callback = null;
var self = this;
insertAll(self, Array.isArray(docs) ? docs : [docs], options, callback);
return this;
};
/**
* @ignore
*/
var checkCollectionName = function checkCollectionName (collectionName) {
if ('string' !== typeof collectionName) {
throw Error("collection name must be a String");
}
if (!collectionName || collectionName.indexOf('..') != -1) {
throw Error("collection names cannot be empty");
}
if (collectionName.indexOf('$') != -1 &&
collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) {
throw Error("collection names must not contain '$'");
}
if (collectionName.match(/^\.|\.$/) != null) {
throw Error("collection names must not start or end with '.'");
}
};
/**
* Removes documents specified by `selector` from the db.
*
* 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 {Object} [selector] optional select, no selector is equivalent to removing all documents.
* @param {Object} [options] additional options during remove.
* @param {Function} [callback] must be provided if you performing a safe remove
* @return {null}
* @api public
*/
Collection.prototype.remove = function remove(selector, options, callback) {
if ('function' === typeof selector) {
callback = selector;
selector = options = {};
} else if ('function' === typeof options) {
callback = options;
options = {};
}
// Ensure options
if(options == null) options = {};
if(!('function' === typeof callback)) callback = null;
// Ensure we have at least an empty selector
selector = selector == null ? {} : selector;
var deleteCommand = new DeleteCommand(
this.db
, this.db.databaseName + "." + this.collectionName
, selector);
var self = this;
var errorOptions = options.safe != null ? options.safe : null;
errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
errorOptions = errorOptions == null && this.db.strict != null ? this.db.strict : errorOptions;
// If we have a write concern set and no callback throw error
if(errorOptions && errorOptions['safe'] != false && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
// Execute the command, do not add a callback as it's async
if (options && options.safe || this.opts.safe != null || this.db.strict) {
// Insert options
var commandOptions = {read:false};
// If we have safe set set async to false
if(errorOptions == null) commandOptions['async'] = true;
// Set safe option
commandOptions['safe'] = true;
// If we have an error option
if(typeof errorOptions == 'object') {
var keys = Object.keys(errorOptions);
for(var i = 0; i < keys.length; i++) {
commandOptions[keys[i]] = errorOptions[keys[i]];
}
}
// Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection)
this.db._executeRemoveCommand(deleteCommand, commandOptions, function (err, error) {
error = error && error.documents;
if(!callback) return;
if(err) {
callback(err);
} else if(error[0].err || error[0].errmsg) {
callback(self.db.wrap(error[0]));
} else {
callback(null, error[0].n);
}
});
} else {
var result = this.db._executeRemoveCommand(deleteCommand);
// If no callback just return
if (!callback) return;
// If error return error
if (result instanceof Error) {
return callback(result);
}
// Otherwise just return
return callback();
}
};
/**
* Renames the collection.
*
* @param {String} newName the new name of the collection.
* @param {Function} callback the callback accepting the result
* @return {null}
* @api public
*/
Collection.prototype.rename = function rename (newName, callback) {
var self = this;
// Ensure the new name is valid
checkCollectionName(newName);
// Execute the command, return the new renamed collection if successful
self.db._executeQueryCommand(DbCommand.createRenameCollectionCommand(self.db, self.collectionName, newName), function(err, result) {
if(err == null && result.documents[0].ok == 1) {
if(callback != null) {
// Set current object to point to the new name
self.collectionName = newName;
// Return the current collection
callback(null, self);
}
} else if(result.documents[0].errmsg != null) {
if(callback != null) {
err != null ? callback(err, null) : callback(self.db.wrap(result.documents[0]), null);
}
}
});
};
/**
* @ignore
*/
var insertAll = function insertAll (self, docs, options, callback) {
if('function' === typeof options) callback = options, options = {};
if(options == null) options = {};
if(!('function' === typeof callback)) callback = null;
// Insert options (flags for insert)
var insertFlags = {};
// If we have a mongodb version >= 1.9.1 support keepGoing attribute
if(options['keepGoing'] != null) {
insertFlags['keepGoing'] = options['keepGoing'];
}
// Either use override on the function, or go back to default on either the collection
// level or db
if(options['serializeFunctions'] != null) {
insertFlags['serializeFunctions'] = options['serializeFunctions'];
} else {
insertFlags['serializeFunctions'] = self.serializeFunctions;
}
// Pass in options
var insertCommand = new InsertCommand(
self.db
, self.db.databaseName + "." + self.collectionName, true, insertFlags);
// Add the documents and decorate them with id's if they have none
for (var index = 0, len = docs.length; index < len; ++index) {
var doc = docs[index];
// Add id to each document if it's not already defined
if (!(Buffer.isBuffer(doc)) && doc['_id'] == null && self.db.forceServerObjectId != true) {
doc['_id'] = self.pkFactory.createPk();
}
insertCommand.add(doc);
}
// Collect errorOptions
var errorOptions = options.safe != null ? options.safe : null;
errorOptions = errorOptions == null && self.opts.safe != null ? self.opts.safe : errorOptions;
errorOptions = errorOptions == null && self.db.strict != null ? self.db.strict : errorOptions;
// If we have a write concern set and no callback throw error
if(errorOptions && errorOptions['safe'] != false && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
// Default command options
var commandOptions = {};
// If safe is defined check for error message
if(errorOptions && errorOptions != false) {
// Insert options
commandOptions['read'] = false;
// If we have safe set set async to false
if(errorOptions == null) commandOptions['async'] = true;
// Set safe option
commandOptions['safe'] = errorOptions;
// If we have an error option
if(typeof errorOptions == 'object') {
var keys = Object.keys(errorOptions);
for(var i = 0; i < keys.length; i++) {
commandOptions[keys[i]] = errorOptions[keys[i]];
}
}
// Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection)
self.db._executeInsertCommand(insertCommand, commandOptions, function (err, error) {
error = error && error.documents;
if(!callback) return;
if (err) {
callback(err);
} else if(error[0].err || error[0].errmsg) {
callback(self.db.wrap(error[0]));
} else {
callback(null, docs);
}
});
} else {
var result = self.db._executeInsertCommand(insertCommand, commandOptions);
// If no callback just return
if(!callback) return;
// If error return error
if(result instanceof Error) {
return callback(result);
}
// Otherwise just return
return callback(null, docs);
}
};
/**
* Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic
* operators and update instead for more efficient operations.
*
* 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 {Object} [doc] the document to save
* @param {Object} [options] additional options during remove.
* @param {Function} [callback] must be provided if you performing a safe save
* @return {null}
* @api public
*/
Collection.prototype.save = function save(doc, options, callback) {
if('function' === typeof options) callback = options, options = null;
if(options == null) options = {};
if(!('function' === typeof callback)) callback = null;
var errorOptions = options.safe != null ? options.safe : false;
errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
// Extract the id, if we have one we need to do a update command
var id = doc['_id'];
if(id) {
this.update({ _id: id }, doc, { upsert: true, safe: errorOptions }, callback);
} else {
this.insert(doc, { safe: errorOptions }, callback && function (err, docs) {
if (err) return callback(err, null);
if (Array.isArray(docs)) {
callback(err, docs[0]);
} else {
callback(err, docs);
}
});
}
};
/**
* Updates documents.
*
* Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
* - **upsert** {Boolean, default:false}, perform an upsert operation.
* - **multi** {Boolean, default:false}, update all documents matching the selector.
* - **serializeFunctions** {Boolean, default:false}, serialize functions on the document.
*
* @param {Object} selector the query to select the document/documents to be updated
* @param {Object} document the fields/vals to be updated, or in the case of an upsert operation, inserted.
* @param {Object} [options] additional options during update.
* @param {Function} [callback] must be provided if you performing a safe update
* @return {null}
* @api public
*/
Collection.prototype.update = function update(selector, document, options, callback) {
if('function' === typeof options) callback = options, options = null;
if(options == null) options = {};
if(!('function' === typeof callback)) callback = null;
// Either use override on the function, or go back to default on either the collection
// level or db
if(options['serializeFunctions'] != null) {
options['serializeFunctions'] = options['serializeFunctions'];
} else {
options['serializeFunctions'] = this.serializeFunctions;
}
var updateCommand = new UpdateCommand(
this.db
, this.db.databaseName + "." + this.collectionName
, selector
, document
, options);
var self = this;
// Unpack the error options if any
var errorOptions = (options && options.safe != null) ? options.safe : null;
errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
errorOptions = errorOptions == null && this.db.strict != null ? this.db.strict : errorOptions;
// If we have a write concern set and no callback throw error
if(errorOptions && errorOptions['safe'] != false && typeof callback !== 'function') throw new Error("safe cannot be used without a callback");
// If we are executing in strict mode or safe both the update and the safe command must happen on the same line
if(errorOptions && errorOptions != false) {
// Insert options
var commandOptions = {read:false};
// If we have safe set set async to false
if(errorOptions == null) commandOptions['async'] = true;
// Set safe option
commandOptions['safe'] = true;
// If we have an error option
if(typeof errorOptions == 'object') {
var keys = Object.keys(errorOptions);
for(var i = 0; i < keys.length; i++) {
commandOptions[keys[i]] = errorOptions[keys[i]];
}
}
// Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection)
this.db._executeUpdateCommand(updateCommand, commandOptions, function (err, error) {
error = error && error.documents;
if(!callback) return;
if(err) {
callback(err);
} else if(error[0].err || error[0].errmsg) {
callback(self.db.wrap(error[0]));
} else {
// Perform the callback
callback(null, error[0].n, error[0]);
}
});
} else {
// Execute update
var result = this.db._executeUpdateCommand(updateCommand);
// If no callback just return
if (!callback) return;
// If error return error
if (result instanceof Error) {
return callback(result);
}
// Otherwise just return
return callback();
}
};
/**
* The distinct command returns returns a list of distinct values for the given key across a collection.
*
* @param {String} key key to run distinct against.
* @param {Object} [query] option query to narrow the returned objects.
* @param {Function} callback must be provided.
* @return {null}
* @api public
*/
Collection.prototype.distinct = function distinct(key, query, callback) {
if ('function' === typeof query) callback = query, query = {};
var mapCommandHash = {
distinct: this.collectionName
, query: query
, key: key
};
var cmd = DbCommand.createDbSlaveOkCommand(this.db, mapCommandHash);
this.db._executeQueryCommand(cmd, {read:true}, function (err, result) {
if (err) {
return callback(err);
}
if (result.documents[0].ok != 1) {
return callback(new Error(result.documents[0].errmsg));
}
callback(null, result.documents[0].values);
});
};
/**
* Count number of matching documents in the db to a query.
*
* @param {Object} [query] query to filter by before performing count.
* @param {Function} callback must be provided.
* @return {null}
* @api public
*/
Collection.prototype.count = function count (query, callback) {
if ('function' === typeof query) callback = query, query = {};
var final_query = {
count: this.collectionName
, query: query
, fields: null
};
var queryOptions = QueryCommand.OPTS_NO_CURSOR_TIMEOUT;
if (this.slaveOk || this.db.slaveOk) {
queryOptions |= QueryCommand.OPTS_SLAVE;
}
var queryCommand = new QueryCommand(
this.db
, this.db.databaseName + ".$cmd"
, queryOptions
, 0
, -1
, final_query
, null
);
var self = this;
this.db._executeQueryCommand(queryCommand, {read:true}, function (err, result) {
result = result && result.documents;
if(!callback) return;
if (err) {
callback(err);
} else if (result[0].ok != 1 || result[0].errmsg) {
callback(self.db.wrap(result[0]));
} else {
callback(null, result[0].n);
}
});
};
/**
* Drop the collection
*
* @param {Function} [callback] provide a callback to be notified when command finished executing
* @return {null}
* @api public
*/
Collection.prototype.drop = function drop(callback) {
this.db.dropCollection(this.collectionName, callback);
};
/**
* Find and update a document.
*
* Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
* - **remove** {Boolean, default:false}, set to true to remove the object before returning.
* - **upsert** {Boolean, default:false}, perform an upsert operation.
* - **new** {Boolean, default:false}, set to true if you want to return the modified object rather than the original. Ignored for remove.
*
* @param {Object} query query object to locate the object to modify
* @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate
* @param {Object} doc - the fields/vals to be updated
* @param {Object} [options] additional options during update.
* @param {Function} [callback] returns results.
* @return {null}
* @api public
*/
Collection.prototype.findAndModify = function findAndModify (query, sort, doc, options, callback) {
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
sort = args.length ? args.shift() : [];
doc = args.length ? args.shift() : null;
options = args.length ? args.shift() : {};
var self = this;
var queryObject = {
'findandmodify': this.collectionName
, 'query': query
, 'sort': utils.formattedOrderClause(sort)
};
queryObject.new = options.new ? 1 : 0;
queryObject.remove = options.remove ? 1 : 0;
queryObject.upsert = options.upsert ? 1 : 0;
if (options.fields) {
queryObject.fields = options.fields;
}
if (doc && !options.remove) {
queryObject.update = doc;
}
// Either use override on the function, or go back to default on either the collection
// level or db
if(options['serializeFunctions'] != null) {
options['serializeFunctions'] = options['serializeFunctions'];
} else {
options['serializeFunctions'] = this.serializeFunctions;
}
// Unpack the error options if any
var errorOptions = (options && options.safe != null) ? options.safe : null;
errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
errorOptions = errorOptions == null && this.db.strict != null ? this.db.strict : errorOptions;
// Commands to send
var commands = [];
// Add the find and modify command
commands.push(DbCommand.createDbSlaveOkCommand(this.db, queryObject, options));
// If we have safe defined we need to return both call results
var chainedCommands = errorOptions != null ? true : false;
// Add error command if we have one
if(chainedCommands) {
commands.push(DbCommand.createGetLastErrorCommand(errorOptions, this.db));
}
// Fire commands and
this.db._executeQueryCommand(commands, function(err, result) {
result = result && result.documents;
if(err != null) {
callback(err);
} else if(result[0].err != null) {
callback(self.db.wrap(result[0]), null);
} else if(result[0].errmsg != null && !result[0].errmsg.match(eErrorMessages)) {
// Workaround due to 1.8.X returning an error on no matching object
// while 2.0.X does not not, making 2.0.X behaviour standard
callback(self.db.wrap(result[0]), null);
} else {
return callback(null, result[0].value);
}
});
}
/**
* Find and remove a document
*
* 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 {Object} query query object to locate the object to modify
* @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate
* @param {Object} [options] additional options during update.
* @param {Function} [callback] returns results.
* @return {null}
* @api public
*/
Collection.prototype.findAndRemove = function(query, sort, options, callback) {
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
sort = args.length ? args.shift() : [];
options = args.length ? args.shift() : {};
// Add the remove option
options['remove'] = true;
// Execute the callback
this.findAndModify(query, sort, null, options, callback);
}
var testForFields = {'limit' : 1, 'sort' : 1, 'fields' : 1, 'skip' : 1, 'hint' : 1, 'explain' : 1, 'snapshot' : 1
, 'timeout' : 1, 'tailable' : 1, 'batchSize' : 1, 'raw' : 1, 'read' : 1
, 'returnKey' : 1, 'maxScan' : 1, 'min' : 1, 'max' : 1, 'showDiskLoc' : 1, 'comment' : 1};
/**
* Creates a cursor for a query that can be used to iterate over results from MongoDB
*
* Various argument possibilities
* - callback?
* - selector, callback?,
* - selector, fields, callback?
* - selector, options, callback?
* - selector, fields, options, callback?
* - selector, fields, skip, limit, callback?
* - selector, fields, skip, limit, timeout, callback?
*
* Options
* - **limit** {Number, default:0}, sets the limit of documents returned in the query.
* - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
* - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
* - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination).
* - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
* - **explain** {Boolean, default:false}, explain the query instead of returning the data.
* - **snapshot** {Boolean, default:false}, snapshot query.
* - **timeout** {Boolean, default:false}, specify if the cursor can timeout.
* - **tailable** {Boolean, default:false}, specify if the cursor is tailable.
* - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results.
* - **returnKey** {Boolean, default:false}, only return the index key.
* - **maxScan** {Number}, Limit the number of items to scan.
* - **min** {Number}, Set index bounds.
* - **max** {Number}, Set index bounds.
* - **showDiskLoc** {Boolean, default:false}, Show disk location of results.
* - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler.
* - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents.
* - **read** {Boolean, default:false}, Tell the query to read from a secondary server.
*
* @param {Object} query query object to locate the object to modify
* @param {Object} [options] additional options during update.
* @param {Function} [callback] optional callback for cursor.
* @return {Cursor} returns a cursor to the query
* @api public
*/
Collection.prototype.find = function find () {
var options
, args = Array.prototype.slice.call(arguments, 0)
, has_callback = typeof args[args.length - 1] === 'function'
, has_weird_callback = typeof args[0] === 'function'
, callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null)
, len = args.length
, selector = len >= 1 ? args[0] : {}
, fields = len >= 2 ? args[1] : undefined;
if(len === 1 && has_weird_callback) {
// backwards compat for callback?, options case
selector = {};
options = args[0];
}
if(len === 2 && !Array.isArray(fields)) {
var fieldKeys = Object.getOwnPropertyNames(fields);
var is_option = false;
for(var i = 0; i < fieldKeys.length; i++) {
if(testForFields[fieldKeys[i]] != null) {
is_option = true;
break;
}
}
if(is_option) {
options = fields;
fields = undefined;
} else {
options = {};
}
} else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) {
var newFields = {};
// Rewrite the array
for(var i = 0; i < fields.length; i++) {
newFields[fields[i]] = 1;
}
// Set the fields
fields = newFields;
}
if(3 === len) {
options = args[2];
}
// Ensure selector is not null
selector = selector == null ? {} : selector;
// Validate correctness off the selector
var object = selector;
if(Buffer.isBuffer(object)) {
var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
if(object_size != object.length) {
var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
error.name = 'MongoError';
throw error;
}
}
// Validate correctness of the field selector
var object = fields;
if(Buffer.isBuffer(object)) {
var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
if(object_size != object.length) {
var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
error.name = 'MongoError';
throw error;
}
}
// Check special case where we are using an objectId
if(selector instanceof ObjectID) {
selector = {_id:selector};
}
// If it's a serialized fields field we need to just let it through
// user be warned it better be good
if(options && options.fields && !(Buffer.isBuffer(options.fields))) {
fields = {};
if(Array.isArray(options.fields)) {
if(!options.fields.length) {
fields['_id'] = 1;
} else {
for (var i = 0, l = options.fields.length; i < l; i++) {
fields[options.fields[i]] = 1;
}
}
} else {
fields = options.fields;
}
}
if (!options) options = {};
options.skip = len > 3 ? args[2] : options.skip ? options.skip : 0;
options.limit = len > 3 ? args[3] : options.limit ? options.limit : 0;
options.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.raw;
options.hint = options.hint != null ? normalizeHintField(options.hint) : this.internalHint;
options.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout;
// If we have overridden slaveOk otherwise use the default db setting
options.slaveOk = options.slaveOk != null ? options.slaveOk : this.db.slaveOk;
var o = options;
// callback for backward compatibility
if(callback) {
// TODO refactor Cursor args
callback(null, new Cursor(this.db, this, selector, fields, o.skip, o.limit
, o.sort, o.hint, o.explain, o.snapshot, o.timeout, o.tailable, o.batchSize
, o.slaveOk, o.raw, o.read, o.returnKey, o.maxScan, o.min, o.max, o.showDiskLoc, o.comment));
} else {
return new Cursor(this.db, this, selector, fields, o.skip, o.limit
, o.sort, o.hint, o.explain, o.snapshot, o.timeout, o.tailable, o.batchSize
, o.slaveOk, o.raw, o.read, o.returnKey, o.maxScan, o.min, o.max, o.showDiskLoc, o.comment);
}
};
/**
* Normalizes a `hint` argument.
*
* @param {String|Object|Array} hint
* @return {Object}
* @api private
*/
var normalizeHintField = function normalizeHintField(hint) {
var finalHint = null;
if (null != hint) {
switch (hint.constructor) {
case String:
finalHint = {};
finalHint[hint] = 1;
break;
case Object:
finalHint = {};
for (var name in hint) {
finalHint[name] = hint[name];
}
break;
case Array:
finalHint = {};
hint.forEach(function(param) {
finalHint[param] = 1;
});
break;
}
}
return finalHint;
};
/**
* Finds a single document based on the query
*
* Various argument possibilities
* - callback?
* - selector, callback?,
* - selector, fields, callback?
* - selector, options, callback?
* - selector, fields, options, callback?
* - selector, fields, skip, limit, callback?
* - selector, fields, skip, limit, timeout, callback?
*
* Options
* - **limit** {Number, default:0}, sets the limit of documents returned in the query.
* - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
* - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
* - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination).
* - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
* - **explain** {Boolean, default:false}, explain the query instead of returning the data.
* - **snapshot** {Boolean, default:false}, snapshot query.
* - **timeout** {Boolean, default:false}, specify if the cursor can timeout.
* - **tailable** {Boolean, default:false}, specify if the cursor is tailable.
* - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results.
* - **returnKey** {Boolean, default:false}, only return the index key.
* - **maxScan** {Number}, Limit the number of items to scan.
* - **min** {Number}, Set index bounds.
* - **max** {Number}, Set index bounds.
* - **showDiskLoc** {Boolean, default:false}, Show disk location of results.
* - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler.
* - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents.
* - **read** {Boolean, default:false}, Tell the query to read from a secondary server.
*
* @param {Object} query query object to locate the object to modify
* @param {Object} [options] additional options during update.
* @param {Function} [callback] optional callback for cursor.
* @return {Cursor} returns a cursor to the query
* @api public
*/
Collection.prototype.findOne = function findOne () {
var self = this;
var args = Array.prototype.slice.call(arguments, 0);
var callback = args.pop();
var cursor = this.find.apply(this, args).limit(-1).batchSize(1);
// Return the item
cursor.toArray(function(err, items) {
if(err != null) return callback(err instanceof Error ? err : self.db.wrap(new Error(err)), null);
if(items.length == 1) return callback(null, items[0]);
callback(null, null);
});
};
/**
* Creates an index on the collection.
*
* Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a
* - **unique** {Boolean, default:false}, creates an unique index.
* - **sparse** {Boolean, default:false}, creates a sparse index.
* - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible.
* - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
* - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates.
* - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates.
*
* @param {Object} fieldOrSpec fieldOrSpec that defines the index.
* @param {Object} [options] additional options during update.
* @param {Function} callback for results.
* @return {null}
* @api public
*/
Collection.prototype.createIndex = function createIndex (fieldOrSpec, options, callback) {
// Clean up call
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
options = args.length ? args.shift() : {};
options = typeof callback === 'function' ? options : callback;
options = options == null ? {} : options;
// Collect errorOptions
var errorOptions = options.safe != null ? options.safe : null;
errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
errorOptions = errorOptions == null && this.db.strict != null ? this.db.strict : errorOptions;
// If we have a write concern set and no callback throw error
if(errorOptions != null && errorOptions != false && (typeof callback !== 'function' && typeof options !== 'function')) throw new Error("safe cannot be used without a callback");
// Execute create index
this.db.createIndex(this.collectionName, fieldOrSpec, options, callback);
};
/**
* Ensures that an index exists, if it does not it creates it
*
* Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a
* - **unique** {Boolean, default:false}, creates an unique index.
* - **sparse** {Boolean, default:false}, creates a sparse index.
* - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible.
* - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
* - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates.
* - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates.
* - **v** {Number}, specify the format version of the indexes.
*
* @param {Object} fieldOrSpec fieldOrSpec that defines the index.
* @param {Object} [options] additional options during update.
* @param {Function} callback for results.
* @return {null}
* @api public
*/
Collection.prototype.ensureIndex = function ensureIndex (fieldOrSpec, options, callback) {
// Clean up call
if (typeof callback === 'undefined' && typeof options === 'function') {
callback = options;
options = {};
}
if (options == null) {
options = {};
}
// Collect errorOptions
var errorOptions = options.safe != null ? options.safe : null;
errorOptions = errorOptions == null && this.opts.safe != null ? this.opts.safe : errorOptions;
errorOptions = errorOptions == null && this.db.strict != null ? this.db.strict : errorOptions;
// If we have a write concern set and no callback throw error
if(errorOptions != null && errorOptions != false && (typeof callback !== 'function' && typeof options !== 'function')) throw new Error("safe cannot be used without a callback");
// Execute create index
this.db.ensureIndex(this.collectionName, fieldOrSpec, options, callback);
};
/**
* Retrieves this collections index info.
*
* Options
* - **full** {Boolean, default:false}, returns the full raw index information.
*
* @param {Object} [options] additional options during update.
* @param {Function} callback returns the index information.
* @return {null}
* @api public
*/
Collection.prototype.indexInformation = function indexInformation (options, callback) {
// Unpack calls
var args = Array.prototype.slice.call(arguments, 0);
callback = args.pop();
options = args.length ? args.shift() : {};
// Call the index information
this.db.indexInformation(this.collectionName, options, callback);
};
/**
* Drops an index from this collection.
*
* @param {String} name
* @param {Function} callback returns the results.
* @return {null}
* @api public
*/
Collection.prototype.dropIndex = function dropIndex (name, callback) {
this.db.dropIndex(this.collectionName, name, callback);