-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimongo.js
4087 lines (3995 loc) · 448 KB
/
minimongo.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
//////////////////////////////////////////////////////////////////////////
// //
// This is a generated file. You can view the original //
// source in your browser if your browser supports source maps. //
// //
// If you are using Chrome, open the Developer Tools and click the gear //
// icon in its lower right corner. In the General Settings panel, turn //
// on 'Enable source maps'. //
// //
// If you are using Firefox 23, go to `about:config` and set the //
// `devtools.debugger.source-maps-enabled` preference to true. //
// (The preference should be on by default in Firefox 24; versions //
// older than 23 do not support source maps.) //
// //
//////////////////////////////////////////////////////////////////////////
define(function (require) {
var Package = {};
var Meteor = require('./meteor');
var _ = require('underscore');
var EJSON = require('./ejson');
var EJSONTest = EJSON._EJSONTest;
var IdMap = require('./id-map');
var OrderedDict = require('./ordered-dict');
var Tracker = require('./tracker');
var Deps = Tracker._Deps;
var Random = require('./random');
var GeoJSON = require('./geojson-utils');
/* Package-scope variables */
var LocalCollection, Minimongo, MinimongoTest, MinimongoError, isArray, isPlainObject, isIndexable, isOperatorObject, isNumericKey, regexpElementMatcher, equalityElementMatcher, ELEMENT_OPERATORS, makeLookupFunction, expandArraysInBranches, projectionDetails, pathsToTree;
(function () {
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// packages/minimongo/minimongo.js //
// //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// XXX type checking on selectors (graceful error if malformed) // 1
// 2
// LocalCollection: a set of documents that supports queries and modifiers. // 3
// 4
// Cursor: a specification for a particular subset of documents, w/ // 5
// a defined order, limit, and offset. creating a Cursor with LocalCollection.find(), // 6
// 7
// ObserveHandle: the return value of a live query. // 8
// 9
LocalCollection = function (name) { // 10
var self = this; // 11
self.name = name; // 12
// _id -> document (also containing id) // 13
self._docs = new LocalCollection._IdMap; // 14
// 15
self._observeQueue = new Meteor._SynchronousQueue(); // 16
// 17
self.next_qid = 1; // live query id generator // 18
// 19
// qid -> live query object. keys: // 20
// ordered: bool. ordered queries have addedBefore/movedBefore callbacks. // 21
// results: array (ordered) or object (unordered) of current results // 22
// (aliased with self._docs!) // 23
// resultsSnapshot: snapshot of results. null if not paused. // 24
// cursor: Cursor object for the query. // 25
// selector, sorter, (callbacks): functions // 26
self.queries = {}; // 27
// 28
// null if not saving originals; an IdMap from id to original document value if // 29
// saving originals. See comments before saveOriginals(). // 30
self._savedOriginals = null; // 31
// 32
// True when observers are paused and we should not send callbacks. // 33
self.paused = false; // 34
}; // 35
// 36
Minimongo = {}; // 37
// 38
// Object exported only for unit testing. // 39
// Use it to export private functions to test in Tinytest. // 40
MinimongoTest = {}; // 41
// 42
LocalCollection._applyChanges = function (doc, changeFields) { // 43
_.each(changeFields, function (value, key) { // 44
if (value === undefined) // 45
delete doc[key]; // 46
else // 47
doc[key] = value; // 48
}); // 49
}; // 50
// 51
MinimongoError = function (message) { // 52
var e = new Error(message); // 53
e.name = "MinimongoError"; // 54
return e; // 55
}; // 56
// 57
// 58
// options may include sort, skip, limit, reactive // 59
// sort may be any of these forms: // 60
// {a: 1, b: -1} // 61
// [["a", "asc"], ["b", "desc"]] // 62
// ["a", ["b", "desc"]] // 63
// (in the first form you're beholden to key enumeration order in // 64
// your javascript VM) // 65
// // 66
// reactive: if given, and false, don't register with Tracker (default // 67
// is true) // 68
// // 69
// XXX possibly should support retrieving a subset of fields? and // 70
// have it be a hint (ignored on the client, when not copying the // 71
// doc?) // 72
// // 73
// XXX sort does not yet support subkeys ('a.b') .. fix that! // 74
// XXX add one more sort form: "key" // 75
// XXX tests // 76
LocalCollection.prototype.find = function (selector, options) { // 77
// default syntax for everything is to omit the selector argument. // 78
// but if selector is explicitly passed in as false or undefined, we // 79
// want a selector that matches nothing. // 80
if (arguments.length === 0) // 81
selector = {}; // 82
// 83
return new LocalCollection.Cursor(this, selector, options); // 84
}; // 85
// 86
// don't call this ctor directly. use LocalCollection.find(). // 87
// 88
LocalCollection.Cursor = function (collection, selector, options) { // 89
var self = this; // 90
if (!options) options = {}; // 91
// 92
self.collection = collection; // 93
self.sorter = null; // 94
// 95
if (LocalCollection._selectorIsId(selector)) { // 96
// stash for fast path // 97
self._selectorId = selector; // 98
self.matcher = new Minimongo.Matcher(selector); // 99
} else { // 100
self._selectorId = undefined; // 101
self.matcher = new Minimongo.Matcher(selector); // 102
if (self.matcher.hasGeoQuery() || options.sort) { // 103
self.sorter = new Minimongo.Sorter(options.sort || [], // 104
{ matcher: self.matcher }); // 105
} // 106
} // 107
self.skip = options.skip; // 108
self.limit = options.limit; // 109
self.fields = options.fields; // 110
// 111
self._projectionFn = LocalCollection._compileProjection(self.fields || {}); // 112
// 113
self._transform = LocalCollection.wrapTransform(options.transform); // 114
// 115
// by default, queries register w/ Tracker when it is available. // 116
if (typeof Tracker !== "undefined") // 117
self.reactive = (options.reactive === undefined) ? true : options.reactive; // 118
}; // 119
// 120
// Since we don't actually have a "nextObject" interface, there's really no // 121
// reason to have a "rewind" interface. All it did was make multiple calls // 122
// to fetch/map/forEach return nothing the second time. // 123
// XXX COMPAT WITH 0.8.1 // 124
LocalCollection.Cursor.prototype.rewind = function () { // 125
}; // 126
// 127
LocalCollection.prototype.findOne = function (selector, options) { // 128
if (arguments.length === 0) // 129
selector = {}; // 130
// 131
// NOTE: by setting limit 1 here, we end up using very inefficient // 132
// code that recomputes the whole query on each update. The upside is // 133
// that when you reactively depend on a findOne you only get // 134
// invalidated when the found object changes, not any object in the // 135
// collection. Most findOne will be by id, which has a fast path, so // 136
// this might not be a big deal. In most cases, invalidation causes // 137
// the called to re-query anyway, so this should be a net performance // 138
// improvement. // 139
options = options || {}; // 140
options.limit = 1; // 141
// 142
return this.find(selector, options).fetch()[0]; // 143
}; // 144
// 145
/** // 146
* @callback IterationCallback // 147
* @param {Object} doc // 148
* @param {Number} index // 149
*/ // 150
/** // 151
* @summary Call `callback` once for each matching document, sequentially and synchronously. // 152
* @locus Anywhere // 153
* @method forEach // 154
* @instance // 155
* @memberOf Mongo.Cursor // 156
* @param {IterationCallback} callback Function to call. It will be called with three arguments: the document, a 0-based index, and <em>cursor</em> itself.
* @param {Any} [thisArg] An object which will be the value of `this` inside `callback`. // 158
*/ // 159
LocalCollection.Cursor.prototype.forEach = function (callback, thisArg) { // 160
var self = this; // 161
// 162
var objects = self._getRawObjects({ordered: true}); // 163
// 164
if (self.reactive) { // 165
self._depend({ // 166
addedBefore: true, // 167
removed: true, // 168
changed: true, // 169
movedBefore: true}); // 170
} // 171
// 172
_.each(objects, function (elt, i) { // 173
// This doubles as a clone operation. // 174
elt = self._projectionFn(elt); // 175
// 176
if (self._transform) // 177
elt = self._transform(elt); // 178
callback.call(thisArg, elt, i, self); // 179
}); // 180
}; // 181
// 182
LocalCollection.Cursor.prototype.getTransform = function () { // 183
return this._transform; // 184
}; // 185
// 186
/** // 187
* @summary Map callback over all matching documents. Returns an Array. // 188
* @locus Anywhere // 189
* @method map // 190
* @instance // 191
* @memberOf Mongo.Cursor // 192
* @param {IterationCallback} callback Function to call. It will be called with three arguments: the document, a 0-based index, and <em>cursor</em> itself.
* @param {Any} [thisArg] An object which will be the value of `this` inside `callback`. // 194
*/ // 195
LocalCollection.Cursor.prototype.map = function (callback, thisArg) { // 196
var self = this; // 197
var res = []; // 198
self.forEach(function (doc, index) { // 199
res.push(callback.call(thisArg, doc, index, self)); // 200
}); // 201
return res; // 202
}; // 203
// 204
/** // 205
* @summary Return all matching documents as an Array. // 206
* @memberOf Mongo.Cursor // 207
* @method fetch // 208
* @instance // 209
* @locus Anywhere // 210
* @returns {Object[]} // 211
*/ // 212
LocalCollection.Cursor.prototype.fetch = function () { // 213
var self = this; // 214
var res = []; // 215
self.forEach(function (doc) { // 216
res.push(doc); // 217
}); // 218
return res; // 219
}; // 220
// 221
/** // 222
* @summary Returns the number of documents that match a query. // 223
* @memberOf Mongo.Cursor // 224
* @method count // 225
* @instance // 226
* @locus Anywhere // 227
* @returns {Number} // 228
*/ // 229
LocalCollection.Cursor.prototype.count = function () { // 230
var self = this; // 231
// 232
if (self.reactive) // 233
self._depend({added: true, removed: true}, // 234
true /* allow the observe to be unordered */); // 235
// 236
return self._getRawObjects({ordered: true}).length; // 237
}; // 238
// 239
LocalCollection.Cursor.prototype._publishCursor = function (sub) { // 240
var self = this; // 241
if (! self.collection.name) // 242
throw new Error("Can't publish a cursor from a collection without a name."); // 243
var collection = self.collection.name; // 244
// 245
// XXX minimongo should not depend on mongo-livedata! // 246
return Mongo.Collection._publishCursor(self, sub, collection); // 247
}; // 248
// 249
LocalCollection.Cursor.prototype._getCollectionName = function () { // 250
var self = this; // 251
return self.collection.name; // 252
}; // 253
// 254
LocalCollection._observeChangesCallbacksAreOrdered = function (callbacks) { // 255
if (callbacks.added && callbacks.addedBefore) // 256
throw new Error("Please specify only one of added() and addedBefore()"); // 257
return !!(callbacks.addedBefore || callbacks.movedBefore); // 258
}; // 259
// 260
LocalCollection._observeCallbacksAreOrdered = function (callbacks) { // 261
if (callbacks.addedAt && callbacks.added) // 262
throw new Error("Please specify only one of added() and addedAt()"); // 263
if (callbacks.changedAt && callbacks.changed) // 264
throw new Error("Please specify only one of changed() and changedAt()"); // 265
if (callbacks.removed && callbacks.removedAt) // 266
throw new Error("Please specify only one of removed() and removedAt()"); // 267
// 268
return !!(callbacks.addedAt || callbacks.movedTo || callbacks.changedAt // 269
|| callbacks.removedAt); // 270
}; // 271
// 272
// the handle that comes back from observe. // 273
LocalCollection.ObserveHandle = function () {}; // 274
// 275
// options to contain: // 276
// * callbacks for observe(): // 277
// - addedAt (document, atIndex) // 278
// - added (document) // 279
// - changedAt (newDocument, oldDocument, atIndex) // 280
// - changed (newDocument, oldDocument) // 281
// - removedAt (document, atIndex) // 282
// - removed (document) // 283
// - movedTo (document, oldIndex, newIndex) // 284
// // 285
// attributes available on returned query handle: // 286
// * stop(): end updates // 287
// * collection: the collection this query is querying // 288
// // 289
// iff x is a returned query handle, (x instanceof // 290
// LocalCollection.ObserveHandle) is true // 291
// // 292
// initial results delivered through added callback // 293
// XXX maybe callbacks should take a list of objects, to expose transactions? // 294
// XXX maybe support field limiting (to limit what you're notified on) // 295
// 296
_.extend(LocalCollection.Cursor.prototype, { // 297
/** // 298
* @summary Watch a query. Receive callbacks as the result set changes. // 299
* @locus Anywhere // 300
* @memberOf Mongo.Cursor // 301
* @instance // 302
* @param {Object} callbacks Functions to call to deliver the result set as it changes // 303
*/ // 304
observe: function (options) { // 305
var self = this; // 306
return LocalCollection._observeFromObserveChanges(self, options); // 307
}, // 308
// 309
/** // 310
* @summary Watch a query. Receive callbacks as the result set changes. Only the differences between the old and new documents are passed to the callbacks.
* @locus Anywhere // 312
* @memberOf Mongo.Cursor // 313
* @instance // 314
* @param {Object} callbacks Functions to call to deliver the result set as it changes // 315
*/ // 316
observeChanges: function (options) { // 317
var self = this; // 318
// 319
var ordered = LocalCollection._observeChangesCallbacksAreOrdered(options); // 320
// 321
// there are several places that assume you aren't combining skip/limit with // 322
// unordered observe. eg, update's EJSON.clone, and the "there are several" // 323
// comment in _modifyAndNotify // 324
// XXX allow skip/limit with unordered observe // 325
if (!options._allow_unordered && !ordered && (self.skip || self.limit)) // 326
throw new Error("must use ordered observe (ie, 'addedBefore' instead of 'added') with skip or limit"); // 327
// 328
if (self.fields && (self.fields._id === 0 || self.fields._id === false)) // 329
throw Error("You may not observe a cursor with {fields: {_id: 0}}"); // 330
// 331
var query = { // 332
matcher: self.matcher, // not fast pathed // 333
sorter: ordered && self.sorter, // 334
distances: ( // 335
self.matcher.hasGeoQuery() && ordered && new LocalCollection._IdMap), // 336
resultsSnapshot: null, // 337
ordered: ordered, // 338
cursor: self, // 339
projectionFn: self._projectionFn // 340
}; // 341
var qid; // 342
// 343
// Non-reactive queries call added[Before] and then never call anything // 344
// else. // 345
if (self.reactive) { // 346
qid = self.collection.next_qid++; // 347
self.collection.queries[qid] = query; // 348
} // 349
query.results = self._getRawObjects({ // 350
ordered: ordered, distances: query.distances}); // 351
if (self.collection.paused) // 352
query.resultsSnapshot = (ordered ? [] : new LocalCollection._IdMap); // 353
// 354
// wrap callbacks we were passed. callbacks only fire when not paused and // 355
// are never undefined // 356
// Filters out blacklisted fields according to cursor's projection. // 357
// XXX wrong place for this? // 358
// 359
// furthermore, callbacks enqueue until the operation we're working on is // 360
// done. // 361
var wrapCallback = function (f) { // 362
if (!f) // 363
return function () {}; // 364
return function (/*args*/) { // 365
var context = this; // 366
var args = arguments; // 367
// 368
if (self.collection.paused) // 369
return; // 370
// 371
self.collection._observeQueue.queueTask(function () { // 372
f.apply(context, args); // 373
}); // 374
}; // 375
}; // 376
query.added = wrapCallback(options.added); // 377
query.changed = wrapCallback(options.changed); // 378
query.removed = wrapCallback(options.removed); // 379
if (ordered) { // 380
query.addedBefore = wrapCallback(options.addedBefore); // 381
query.movedBefore = wrapCallback(options.movedBefore); // 382
} // 383
// 384
if (!options._suppress_initial && !self.collection.paused) { // 385
// XXX unify ordered and unordered interface // 386
var each = ordered // 387
? _.bind(_.each, null, query.results) // 388
: _.bind(query.results.forEach, query.results); // 389
each(function (doc) { // 390
var fields = EJSON.clone(doc); // 391
// 392
delete fields._id; // 393
if (ordered) // 394
query.addedBefore(doc._id, self._projectionFn(fields), null); // 395
query.added(doc._id, self._projectionFn(fields)); // 396
}); // 397
} // 398
// 399
var handle = new LocalCollection.ObserveHandle; // 400
_.extend(handle, { // 401
collection: self.collection, // 402
stop: function () { // 403
if (self.reactive) // 404
delete self.collection.queries[qid]; // 405
} // 406
}); // 407
// 408
if (self.reactive && Tracker.active) { // 409
// XXX in many cases, the same observe will be recreated when // 410
// the current autorun is rerun. we could save work by // 411
// letting it linger across rerun and potentially get // 412
// repurposed if the same observe is performed, using logic // 413
// similar to that of Meteor.subscribe. // 414
Tracker.onInvalidate(function () { // 415
handle.stop(); // 416
}); // 417
} // 418
// run the observe callbacks resulting from the initial contents // 419
// before we leave the observe. // 420
self.collection._observeQueue.drain(); // 421
// 422
return handle; // 423
} // 424
}); // 425
// 426
// Returns a collection of matching objects, but doesn't deep copy them. // 427
// // 428
// If ordered is set, returns a sorted array, respecting sorter, skip, and limit // 429
// properties of the query. if sorter is falsey, no sort -- you get the natural // 430
// order. // 431
// // 432
// If ordered is not set, returns an object mapping from ID to doc (sorter, skip // 433
// and limit should not be set). // 434
// // 435
// If ordered is set and this cursor is a $near geoquery, then this function // 436
// will use an _IdMap to track each distance from the $near argument point in // 437
// order to use it as a sort key. If an _IdMap is passed in the 'distances' // 438
// argument, this function will clear it and use it for this purpose (otherwise // 439
// it will just create its own _IdMap). The observeChanges implementation uses // 440
// this to remember the distances after this function returns. // 441
LocalCollection.Cursor.prototype._getRawObjects = function (options) { // 442
var self = this; // 443
options = options || {}; // 444
// 445
// XXX use OrderedDict instead of array, and make IdMap and OrderedDict // 446
// compatible // 447
var results = options.ordered ? [] : new LocalCollection._IdMap; // 448
// 449
// fast path for single ID value // 450
if (self._selectorId !== undefined) { // 451
// If you have non-zero skip and ask for a single id, you get // 452
// nothing. This is so it matches the behavior of the '{_id: foo}' // 453
// path. // 454
if (self.skip) // 455
return results; // 456
// 457
var selectedDoc = self.collection._docs.get(self._selectorId); // 458
if (selectedDoc) { // 459
if (options.ordered) // 460
results.push(selectedDoc); // 461
else // 462
results.set(self._selectorId, selectedDoc); // 463
} // 464
return results; // 465
} // 466
// 467
// slow path for arbitrary selector, sort, skip, limit // 468
// 469
// in the observeChanges case, distances is actually part of the "query" (ie, // 470
// live results set) object. in other cases, distances is only used inside // 471
// this function. // 472
var distances; // 473
if (self.matcher.hasGeoQuery() && options.ordered) { // 474
if (options.distances) { // 475
distances = options.distances; // 476
distances.clear(); // 477
} else { // 478
distances = new LocalCollection._IdMap(); // 479
} // 480
} // 481
// 482
self.collection._docs.forEach(function (doc, id) { // 483
var matchResult = self.matcher.documentMatches(doc); // 484
if (matchResult.result) { // 485
if (options.ordered) { // 486
results.push(doc); // 487
if (distances && matchResult.distance !== undefined) // 488
distances.set(id, matchResult.distance); // 489
} else { // 490
results.set(id, doc); // 491
} // 492
} // 493
// Fast path for limited unsorted queries. // 494
// XXX 'length' check here seems wrong for ordered // 495
if (self.limit && !self.skip && !self.sorter && // 496
results.length === self.limit) // 497
return false; // break // 498
return true; // continue // 499
}); // 500
// 501
if (!options.ordered) // 502
return results; // 503
// 504
if (self.sorter) { // 505
var comparator = self.sorter.getComparator({distances: distances}); // 506
results.sort(comparator); // 507
} // 508
// 509
var idx_start = self.skip || 0; // 510
var idx_end = self.limit ? (self.limit + idx_start) : results.length; // 511
return results.slice(idx_start, idx_end); // 512
}; // 513
// 514
// XXX Maybe we need a version of observe that just calls a callback if // 515
// anything changed. // 516
LocalCollection.Cursor.prototype._depend = function (changers, _allow_unordered) { // 517
var self = this; // 518
// 519
if (Tracker.active) { // 520
var v = new Tracker.Dependency; // 521
v.depend(); // 522
var notifyChange = _.bind(v.changed, v); // 523
// 524
var options = { // 525
_suppress_initial: true, // 526
_allow_unordered: _allow_unordered // 527
}; // 528
_.each(['added', 'changed', 'removed', 'addedBefore', 'movedBefore'], // 529
function (fnName) { // 530
if (changers[fnName]) // 531
options[fnName] = notifyChange; // 532
}); // 533
// 534
// observeChanges will stop() when this computation is invalidated // 535
self.observeChanges(options); // 536
} // 537
}; // 538
// 539
// XXX enforce rule that field names can't start with '$' or contain '.' // 540
// (real mongodb does in fact enforce this) // 541
// XXX possibly enforce that 'undefined' does not appear (we assume // 542
// this in our handling of null and $exists) // 543
LocalCollection.prototype.insert = function (doc, callback) { // 544
var self = this; // 545
doc = EJSON.clone(doc); // 546
// 547
if (!_.has(doc, '_id')) { // 548
// if you really want to use ObjectIDs, set this global. // 549
// Mongo.Collection specifies its own ids and does not use this code. // 550
doc._id = LocalCollection._useOID ? new LocalCollection._ObjectID() // 551
: Random.id(); // 552
} // 553
var id = doc._id; // 554
// 555
if (self._docs.has(id)) // 556
throw MinimongoError("Duplicate _id '" + id + "'"); // 557
// 558
self._saveOriginal(id, undefined); // 559
self._docs.set(id, doc); // 560
// 561
var queriesToRecompute = []; // 562
// trigger live queries that match // 563
for (var qid in self.queries) { // 564
var query = self.queries[qid]; // 565
var matchResult = query.matcher.documentMatches(doc); // 566
if (matchResult.result) { // 567
if (query.distances && matchResult.distance !== undefined) // 568
query.distances.set(id, matchResult.distance); // 569
if (query.cursor.skip || query.cursor.limit) // 570
queriesToRecompute.push(qid); // 571
else // 572
LocalCollection._insertInResults(query, doc); // 573
} // 574
} // 575
// 576
_.each(queriesToRecompute, function (qid) { // 577
if (self.queries[qid]) // 578
self._recomputeResults(self.queries[qid]); // 579
}); // 580
self._observeQueue.drain(); // 581
// 582
// Defer because the caller likely doesn't expect the callback to be run // 583
// immediately. // 584
if (callback) // 585
Meteor.defer(function () { // 586
callback(null, id); // 587
}); // 588
return id; // 589
}; // 590
// 591
// Iterates over a subset of documents that could match selector; calls // 592
// f(doc, id) on each of them. Specifically, if selector specifies // 593
// specific _id's, it only looks at those. doc is *not* cloned: it is the // 594
// same object that is in _docs. // 595
LocalCollection.prototype._eachPossiblyMatchingDoc = function (selector, f) { // 596
var self = this; // 597
var specificIds = LocalCollection._idsMatchedBySelector(selector); // 598
if (specificIds) { // 599
for (var i = 0; i < specificIds.length; ++i) { // 600
var id = specificIds[i]; // 601
var doc = self._docs.get(id); // 602
if (doc) { // 603
var breakIfFalse = f(doc, id); // 604
if (breakIfFalse === false) // 605
break; // 606
} // 607
} // 608
} else { // 609
self._docs.forEach(f); // 610
} // 611
}; // 612
// 613
LocalCollection.prototype.remove = function (selector, callback) { // 614
var self = this; // 615
// 616
// Easy special case: if we're not calling observeChanges callbacks and we're // 617
// not saving originals and we got asked to remove everything, then just empty // 618
// everything directly. // 619
if (self.paused && !self._savedOriginals && EJSON.equals(selector, {})) { // 620
var result = self._docs.size(); // 621
self._docs.clear(); // 622
_.each(self.queries, function (query) { // 623
if (query.ordered) { // 624
query.results = []; // 625
} else { // 626
query.results.clear(); // 627
} // 628
}); // 629
if (callback) { // 630
Meteor.defer(function () { // 631
callback(null, result); // 632
}); // 633
} // 634
return result; // 635
} // 636
// 637
var matcher = new Minimongo.Matcher(selector); // 638
var remove = []; // 639
self._eachPossiblyMatchingDoc(selector, function (doc, id) { // 640
if (matcher.documentMatches(doc).result) // 641
remove.push(id); // 642
}); // 643
// 644
var queriesToRecompute = []; // 645
var queryRemove = []; // 646
for (var i = 0; i < remove.length; i++) { // 647
var removeId = remove[i]; // 648
var removeDoc = self._docs.get(removeId); // 649
_.each(self.queries, function (query, qid) { // 650
if (query.matcher.documentMatches(removeDoc).result) { // 651
if (query.cursor.skip || query.cursor.limit) // 652
queriesToRecompute.push(qid); // 653
else // 654
queryRemove.push({qid: qid, doc: removeDoc}); // 655
} // 656
}); // 657
self._saveOriginal(removeId, removeDoc); // 658
self._docs.remove(removeId); // 659
} // 660
// 661
// run live query callbacks _after_ we've removed the documents. // 662
_.each(queryRemove, function (remove) { // 663
var query = self.queries[remove.qid]; // 664
if (query) { // 665
query.distances && query.distances.remove(remove.doc._id); // 666
LocalCollection._removeFromResults(query, remove.doc); // 667
} // 668
}); // 669
_.each(queriesToRecompute, function (qid) { // 670
var query = self.queries[qid]; // 671
if (query) // 672
self._recomputeResults(query); // 673
}); // 674
self._observeQueue.drain(); // 675
result = remove.length; // 676
if (callback) // 677
Meteor.defer(function () { // 678
callback(null, result); // 679
}); // 680
return result; // 681
}; // 682
// 683
// XXX atomicity: if multi is true, and one modification fails, do // 684
// we rollback the whole operation, or what? // 685
LocalCollection.prototype.update = function (selector, mod, options, callback) { // 686
var self = this; // 687
if (! callback && options instanceof Function) { // 688
callback = options; // 689
options = null; // 690
} // 691
if (!options) options = {}; // 692
// 693
var matcher = new Minimongo.Matcher(selector); // 694
// 695
// Save the original results of any query that we might need to // 696
// _recomputeResults on, because _modifyAndNotify will mutate the objects in // 697
// it. (We don't need to save the original results of paused queries because // 698
// they already have a resultsSnapshot and we won't be diffing in // 699
// _recomputeResults.) // 700
var qidToOriginalResults = {}; // 701
_.each(self.queries, function (query, qid) { // 702
// XXX for now, skip/limit implies ordered observe, so query.results is // 703
// always an array // 704
if ((query.cursor.skip || query.cursor.limit) && ! self.paused) // 705
qidToOriginalResults[qid] = EJSON.clone(query.results); // 706
}); // 707
var recomputeQids = {}; // 708
// 709
var updateCount = 0; // 710
// 711
self._eachPossiblyMatchingDoc(selector, function (doc, id) { // 712
var queryResult = matcher.documentMatches(doc); // 713
if (queryResult.result) { // 714
// XXX Should we save the original even if mod ends up being a no-op? // 715
self._saveOriginal(id, doc); // 716
self._modifyAndNotify(doc, mod, recomputeQids, queryResult.arrayIndices); // 717
++updateCount; // 718
if (!options.multi) // 719
return false; // break // 720
} // 721
return true; // 722
}); // 723
// 724
_.each(recomputeQids, function (dummy, qid) { // 725
var query = self.queries[qid]; // 726
if (query) // 727
self._recomputeResults(query, qidToOriginalResults[qid]); // 728
}); // 729
self._observeQueue.drain(); // 730
// 731
// If we are doing an upsert, and we didn't modify any documents yet, then // 732
// it's time to do an insert. Figure out what document we are inserting, and // 733
// generate an id for it. // 734
var insertedId; // 735
if (updateCount === 0 && options.upsert) { // 736
var newDoc = LocalCollection._removeDollarOperators(selector); // 737
LocalCollection._modify(newDoc, mod, {isInsert: true}); // 738
if (! newDoc._id && options.insertedId) // 739
newDoc._id = options.insertedId; // 740
insertedId = self.insert(newDoc); // 741
updateCount = 1; // 742
} // 743
// 744
// Return the number of affected documents, or in the upsert case, an object // 745
// containing the number of affected docs and the id of the doc that was // 746
// inserted, if any. // 747
var result; // 748
if (options._returnObject) { // 749
result = { // 750
numberAffected: updateCount // 751
}; // 752
if (insertedId !== undefined) // 753
result.insertedId = insertedId; // 754
} else { // 755
result = updateCount; // 756
} // 757
// 758
if (callback) // 759
Meteor.defer(function () { // 760
callback(null, result); // 761
}); // 762
return result; // 763
}; // 764
// 765
// A convenience wrapper on update. LocalCollection.upsert(sel, mod) is // 766
// equivalent to LocalCollection.update(sel, mod, { upsert: true, _returnObject: // 767
// true }). // 768
LocalCollection.prototype.upsert = function (selector, mod, options, callback) { // 769
var self = this; // 770
if (! callback && typeof options === "function") { // 771
callback = options; // 772
options = {}; // 773
} // 774
return self.update(selector, mod, _.extend({}, options, { // 775
upsert: true, // 776
_returnObject: true // 777
}), callback); // 778
}; // 779
// 780
LocalCollection.prototype._modifyAndNotify = function ( // 781
doc, mod, recomputeQids, arrayIndices) { // 782
var self = this; // 783
// 784
var matched_before = {}; // 785
for (var qid in self.queries) { // 786
var query = self.queries[qid]; // 787
if (query.ordered) { // 788
matched_before[qid] = query.matcher.documentMatches(doc).result; // 789
} else { // 790
// Because we don't support skip or limit (yet) in unordered queries, we // 791
// can just do a direct lookup. // 792
matched_before[qid] = query.results.has(doc._id); // 793
} // 794
} // 795
// 796
var old_doc = EJSON.clone(doc); // 797
// 798
LocalCollection._modify(doc, mod, {arrayIndices: arrayIndices}); // 799
// 800
for (qid in self.queries) { // 801
query = self.queries[qid]; // 802
var before = matched_before[qid]; // 803
var afterMatch = query.matcher.documentMatches(doc); // 804
var after = afterMatch.result; // 805
if (after && query.distances && afterMatch.distance !== undefined) // 806
query.distances.set(doc._id, afterMatch.distance); // 807
// 808
if (query.cursor.skip || query.cursor.limit) { // 809
// We need to recompute any query where the doc may have been in the // 810
// cursor's window either before or after the update. (Note that if skip // 811
// or limit is set, "before" and "after" being true do not necessarily // 812
// mean that the document is in the cursor's output after skip/limit is // 813
// applied... but if they are false, then the document definitely is NOT // 814
// in the output. So it's safe to skip recompute if neither before or // 815
// after are true.) // 816
if (before || after) // 817
recomputeQids[qid] = true; // 818
} else if (before && !after) { // 819
LocalCollection._removeFromResults(query, doc); // 820
} else if (!before && after) { // 821
LocalCollection._insertInResults(query, doc); // 822
} else if (before && after) { // 823
LocalCollection._updateInResults(query, doc, old_doc); // 824
} // 825
} // 826
}; // 827
// 828
// XXX the sorted-query logic below is laughably inefficient. we'll // 829
// need to come up with a better datastructure for this. // 830
// // 831
// XXX the logic for observing with a skip or a limit is even more // 832
// laughably inefficient. we recompute the whole results every time! // 833
// 834
LocalCollection._insertInResults = function (query, doc) { // 835
var fields = EJSON.clone(doc); // 836
delete fields._id; // 837
if (query.ordered) { // 838
if (!query.sorter) { // 839
query.addedBefore(doc._id, query.projectionFn(fields), null); // 840
query.results.push(doc); // 841
} else { // 842
var i = LocalCollection._insertInSortedList( // 843
query.sorter.getComparator({distances: query.distances}), // 844
query.results, doc); // 845
var next = query.results[i+1]; // 846
if (next) // 847
next = next._id; // 848
else // 849
next = null; // 850
query.addedBefore(doc._id, query.projectionFn(fields), next); // 851
} // 852
query.added(doc._id, query.projectionFn(fields)); // 853
} else { // 854
query.added(doc._id, query.projectionFn(fields)); // 855
query.results.set(doc._id, doc); // 856
} // 857
}; // 858
// 859
LocalCollection._removeFromResults = function (query, doc) { // 860
if (query.ordered) { // 861
var i = LocalCollection._findInOrderedResults(query, doc); // 862
query.removed(doc._id); // 863
query.results.splice(i, 1); // 864
} else { // 865
var id = doc._id; // in case callback mutates doc // 866
query.removed(doc._id); // 867
query.results.remove(id); // 868
} // 869
}; // 870
// 871
LocalCollection._updateInResults = function (query, doc, old_doc) { // 872
if (!EJSON.equals(doc._id, old_doc._id)) // 873
throw new Error("Can't change a doc's _id while updating"); // 874
var projectionFn = query.projectionFn; // 875
var changedFields = LocalCollection._makeChangedFields( // 876
projectionFn(doc), projectionFn(old_doc)); // 877
// 878
if (!query.ordered) { // 879
if (!_.isEmpty(changedFields)) { // 880
query.changed(doc._id, changedFields); // 881
query.results.set(doc._id, doc); // 882
} // 883
return; // 884
} // 885
// 886
var orig_idx = LocalCollection._findInOrderedResults(query, doc); // 887
// 888
if (!_.isEmpty(changedFields)) // 889
query.changed(doc._id, changedFields); // 890
if (!query.sorter) // 891
return; // 892
// 893
// just take it out and put it back in again, and see if the index // 894
// changes // 895
query.results.splice(orig_idx, 1); // 896
var new_idx = LocalCollection._insertInSortedList( // 897
query.sorter.getComparator({distances: query.distances}), // 898
query.results, doc); // 899
if (orig_idx !== new_idx) { // 900
var next = query.results[new_idx+1]; // 901
if (next) // 902
next = next._id; // 903
else // 904
next = null; // 905
query.movedBefore && query.movedBefore(doc._id, next); // 906
} // 907
}; // 908
// 909
// Recomputes the results of a query and runs observe callbacks for the // 910
// difference between the previous results and the current results (unless // 911
// paused). Used for skip/limit queries. // 912
// // 913
// When this is used by insert or remove, it can just use query.results for the // 914
// old results (and there's no need to pass in oldResults), because these // 915
// operations don't mutate the documents in the collection. Update needs to pass // 916
// in an oldResults which was deep-copied before the modifier was applied. // 917
// // 918
// oldResults is guaranteed to be ignored if the query is not paused. // 919
LocalCollection.prototype._recomputeResults = function (query, oldResults) { // 920
var self = this; // 921
if (! self.paused && ! oldResults) // 922
oldResults = query.results; // 923
if (query.distances) // 924
query.distances.clear(); // 925
query.results = query.cursor._getRawObjects({ // 926
ordered: query.ordered, distances: query.distances}); // 927
// 928
if (! self.paused) { // 929
LocalCollection._diffQueryChanges( // 930
query.ordered, oldResults, query.results, query, // 931
{ projectionFn: query.projectionFn }); // 932
} // 933
}; // 934
// 935
// 936
LocalCollection._findInOrderedResults = function (query, doc) { // 937
if (!query.ordered) // 938
throw new Error("Can't call _findInOrderedResults on unordered query"); // 939
for (var i = 0; i < query.results.length; i++) // 940
if (query.results[i] === doc) // 941
return i; // 942
throw Error("object missing from query"); // 943
}; // 944
// 945
// This binary search puts a value between any equal values, and the first // 946
// lesser value. // 947
LocalCollection._binarySearch = function (cmp, array, value) { // 948
var first = 0, rangeLength = array.length; // 949
// 950
while (rangeLength > 0) { // 951
var halfRange = Math.floor(rangeLength/2); // 952
if (cmp(value, array[first + halfRange]) >= 0) { // 953
first += halfRange + 1; // 954
rangeLength -= halfRange + 1; // 955
} else { // 956