forked from kofrasa/mingo
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmingo.js
2238 lines (2001 loc) · 59.1 KB
/
mingo.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
// Mingo.js 0.6.2
// Copyright (c) 2015 Francis Asante <[email protected]>
// MIT
;
(function (root, undefined) {
"use strict";
// global on the server, window in the browser
var Mingo = {}, previousMingo;
var _;
Mingo.VERSION = '0.6.2';
// backup previous Mingo
if (root != null) {
previousMingo = root.Mingo;
}
Mingo.noConflict = function () {
root.Mingo = previousMingo;
return Mingo;
};
var nativeScriptEnabled = Boolean(((typeof android !== 'undefined' && android && android.widget && android.widget.Button)
|| (typeof UIButton !== 'undefined' && UIButton)));
var nodeEnabled = ('undefined' !== typeof exports && 'undefined' !== typeof require && 'undefined' === typeof window && !nativeScriptEnabled);
var browserifyEnabled = 'undefined' !== typeof exports && 'undefined' !== typeof require;
// Export the Mingo object for Node.js
if (nodeEnabled || nativeScriptEnabled || browserifyEnabled) {
if (typeof module !== 'undefined') {
module.exports = Mingo;
}
_ = require("underscore"); // get a reference to underscore
} else {
root.Mingo = Mingo;
_ = root._; // get a reference to underscore
}
// quick reference for
var primitives = [
_.isString, _.isBoolean, _.isNumber, _.isDate, _.isNull, _.isRegExp
];
function isPrimitive(value) {
for (var i = 0; i < primitives.length; i++) {
if (primitives[i](value)) {
return true;
}
}
return false;
}
/**
* Simplify expression for easy evaluation with query operators map
* @param expr
* @returns {*}
*/
function normalize(expr) {
// normalized primitives
if (isPrimitive(expr)) {
return _.isRegExp(expr) ? {"$regex": expr} : {"$eq": expr};
}
// normalize object expression
if (_.isObject(expr)) {
var keys = _.keys(expr);
var notQuery = _.intersection(ops(OP_QUERY), keys).length === 0;
// no valid query operator found, so we do simple comparison
if (notQuery) {
return {"$eq": expr};
}
// ensure valid regex
if (_.contains(keys, "$regex")) {
var regex = expr['$regex'];
var options = expr['$options'] || "";
var modifiers = "";
if (_.isString(regex)) {
modifiers += (regex.ignoreCase || options.indexOf("i") >= 0) ? "i" : "";
modifiers += (regex.multiline || options.indexOf("m") >= 0) ? "m" : "";
modifiers += (regex.global || options.indexOf("g") >= 0) ? "g" : "";
regex = new RegExp(regex, modifiers);
}
expr['$regex'] = regex;
delete expr['$options'];
}
}
return expr;
}
// Settings used by Mingo internally
var settings = {
key: "_id"
};
/**
* Setup default settings for Mingo
* @param options
*/
Mingo.setup = function (options) {
_.extend(settings, options || {});
};
/**
* Query object to test collection elements with
* @param criteria the pass criteria for the query
* @param projection optional projection specifiers
* @constructor
*/
Mingo.Query = function (criteria, projection) {
if (!(this instanceof Mingo.Query))
return new Mingo.Query(criteria, projection);
this._criteria = criteria;
this._projection = projection;
this._compiled = [];
this._compile();
};
Mingo.Query.prototype = {
_compile: function () {
if (_.isEmpty(this._criteria)) return;
if (_.isArray(this._criteria) || _.isFunction(this._criteria) || !_.isObject(this._criteria)) {
throw new Error("Invalid type for criteria");
}
for (var field in this._criteria) {
if (this._criteria.hasOwnProperty(field)) {
var expr = this._criteria[field];
if (_.contains(['$and', '$or', '$nor', '$where'], field)) {
this._processOperator(field, field, expr);
} else {
// normalize expression
expr = normalize(expr);
for (var op in expr) {
if (expr.hasOwnProperty(op)) {
this._processOperator(field, op, expr[op]);
}
}
}
}
}
},
_processOperator: function (field, operator, value) {
if (_.contains(ops(OP_QUERY), operator)) {
this._compiled.push(queryOperators[operator](field, value));
} else {
throw new Error("Invalid query operator '" + operator + "' detected");
}
},
/**
* Checks if the object passes the query criteria. Returns true if so, false otherwise.
* @param obj
* @returns {boolean}
*/
test: function (obj) {
for (var i = 0; i < this._compiled.length; i++) {
if (!this._compiled[i].test(obj)) {
return false;
}
}
return true;
},
/**
* Performs a query on a collection and returns a cursor object.
* @param collection
* @param projection
* @returns {Mingo.Cursor}
*/
find: function (collection, projection) {
return new Mingo.Cursor(collection, this, projection);
},
/**
* Remove matched documents from the collection returning the remainder
* @param collection
* @returns {Array}
*/
remove: function (collection) {
var arr = [];
for (var i = 0; i < collection.length; i++) {
if (!this.test(collection[i])) {
arr.push(collection[i]);
}
}
return arr;
}
};
if (nodeEnabled) {
var Transform = require('stream').Transform;
var util = require('util');
Mingo.Query.prototype.stream = function (options) {
return new Mingo.Stream(this, options);
};
/**
* Create a Transform class
* @param query
* @param options
* @returns {Mingo.Stream}
* @constructor
*/
Mingo.Stream = function (query, options) {
if (!(this instanceof Mingo.Stream))
return new Mingo.Stream(query, options);
options = options || {};
_.extend(options, {objectMode: true});
Transform.call(this, options);
// query for this stream
this._query = query;
};
// extend Transform
util.inherits(Mingo.Stream, Transform);
Mingo.Stream.prototype._transform = function (chunk, encoding, done) {
if (_.isObject(chunk) && this._query.test(chunk)) {
if (_.isEmpty(this._query._projection)) {
this.push(chunk);
} else {
var cursor = new Mingo.Cursor([chunk], this._query);
if (cursor.hasNext()) {
this.push(cursor.next());
}
}
}
done();
};
}
/**
* Cursor to iterate and perform filtering on matched objects
* @param collection
* @param query
* @param projection
* @constructor
*/
Mingo.Cursor = function (collection, query, projection) {
if (!(this instanceof Mingo.Cursor))
return new Mingo.Cursor(collection, query, projection);
this._query = query;
this._collection = collection;
this._projection = projection || query._projection;
this._operators = {};
this._result = false;
this._position = 0;
};
Mingo.Cursor.prototype = {
_fetch: function () {
var self = this;
if (this._result !== false) {
return this._result;
}
// inject projection operator
if (_.isObject(this._projection)) {
_.extend(this._operators, {"$project": this._projection});
}
// if (!_.isArray(this._collection) && !_.isObject(this._collection)) {
// throw new Error("Input collection is not of valid type. Must be an Array.");
// }
// filter collection
this._result = _.filter(this._collection, this._query.test, this._query);
var pipeline = [];
_.each(['$sort', '$skip', '$limit', '$project'], function (op) {
if (_.has(self._operators, op)) {
pipeline.push(_.pick(self._operators, op));
}
});
if (pipeline.length > 0) {
var aggregator = new Mingo.Aggregator(pipeline);
this._result = aggregator.run(this._result, this._query);
}
return this._result;
},
/**
* Fetch and return all matched results
* @returns {Array}
*/
all: function () {
return this._fetch();
},
/**
* Fetch and return the first matching result
* @returns {Object}
*/
first: function () {
return this.count() > 0 ? this._fetch()[0] : null;
},
/**
* Fetch and return the last matching object from the result
* @returns {Object}
*/
last: function () {
return this.count() > 0 ? this._fetch()[this.count() - 1] : null;
},
/**
* Counts the number of matched objects found
* @returns {Number}
*/
count: function () {
return this._fetch().length;
},
/**
* Returns a cursor that begins returning results only after passing or skipping a number of documents.
* @param {Number} n the number of results to skip.
* @return {Mingo.Cursor} Returns the cursor, so you can chain this call.
*/
skip: function (n) {
_.extend(this._operators, {"$skip": n});
return this;
},
/**
* Constrains the size of a cursor's result set.
* @param {Number} n the number of results to limit to.
* @return {Mingo.Cursor} Returns the cursor, so you can chain this call.
*/
limit: function (n) {
_.extend(this._operators, {"$limit": n});
return this;
},
/**
* Returns results ordered according to a sort specification.
* @param {Object} modifier an object of key and values specifying the sort order. 1 for ascending and -1 for descending
* @return {Mingo.Cursor} Returns the cursor, so you can chain this call.
*/
sort: function (modifier) {
_.extend(this._operators, {"$sort": modifier});
return this;
},
/**
* Returns the next document in a cursor.
* @returns {Object | Boolean}
*/
next: function () {
if (this.hasNext()) {
return this._fetch()[this._position++];
}
return null;
},
/**
* Returns true if the cursor has documents and can be iterated.
* @returns {boolean}
*/
hasNext: function () {
return this.count() > this._position;
},
/**
* Specifies the exclusive upper bound for a specific field
* @param expr
* @returns {Number}
*/
max: function (expr) {
return groupOperators.$max(this._fetch(), expr);
},
/**
* Specifies the inclusive lower bound for a specific field
* @param expr
* @returns {Number}
*/
min: function (expr) {
return groupOperators.$min(this._fetch(), expr);
},
/**
* Applies a function to each document in a cursor and collects the return values in an array.
* @param callback
* @returns {Array}
*/
map: function (callback) {
return _.map(this._fetch(), callback);
},
/**
* Applies a JavaScript function for every document in a cursor.
* @param callback
*/
forEach: function (callback) {
_.each(this._fetch(), callback);
}
};
/**
* Aggregator for defining filter using mongoDB aggregation pipeline syntax
* @param operators an Array of pipeline operators
* @constructor
*/
Mingo.Aggregator = function (operators) {
if (!(this instanceof Mingo.Aggregator))
return new Mingo.Aggregator(operators);
this._operators = operators;
};
Mingo.Aggregator.prototype = {
/**
* Apply the pipeline operations over the collection by order of the sequence added
* @param collection an array of objects to process
* @param query the `Mingo.Query` object to use as context
* @returns {Array}
*/
run: function (collection, query) {
if (!_.isEmpty(this._operators)) {
// run aggregation pipeline
for (var i = 0; i < this._operators.length; i++) {
var operator = this._operators[i];
var key = _.keys(operator);
if (key.length == 1 && _.contains(ops(OP_PIPELINE), key[0])) {
key = key[0];
if (query instanceof Mingo.Query) {
collection = pipelineOperators[key].call(query, collection, operator[key]);
} else {
collection = pipelineOperators[key](collection, operator[key]);
}
} else {
throw new Error("Invalid aggregation operator '" + key + "'");
}
}
}
return collection;
}
};
/**
* Retrieve the value of a given key on an object
* @param obj
* @param field
* @returns {*}
* @private
*/
function getValue(obj, field) {
return _.result(obj, field);
}
/**
* Resolve the value of the field (dot separated) on the given object
* @param obj
* @param field
* @returns {*}
*/
function resolve(obj, field) {
if (!field) {
return undefined;
}
var names = field.split(".");
var value = obj;
var isText;
for (var i = 0; i < names.length; i++) {
isText = names[i].match(/^\d+$/) === null;
if (isText && _.isArray(value)) {
var res = [];
_.each(value, function (item) {
res.push(resolve(item, names[i]));
});
value = res;
} else {
value = getValue(value, names[i]);
}
if (value === undefined) {
break;
}
}
return value;
}
/**
* Performs a query on a collection and returns a cursor object.
* @param collection
* @param criteria
* @param projection
* @returns {Mingo.Cursor}
*/
Mingo.find = function (collection, criteria, projection) {
return (new Mingo.Query(criteria)).find(collection, projection);
};
/**
* Returns a new array without objects which match the criteria
* @param collection
* @param criteria
* @returns {Array}
*/
Mingo.remove = function (collection, criteria) {
return (new Mingo.Query(criteria)).remove(collection);
};
/**
* Return the result collection after running the aggregation pipeline for the given collection
* @param collection
* @param pipeline
* @returns {Array}
*/
Mingo.aggregate = function (collection, pipeline) {
if (!_.isArray(pipeline)) {
throw new Error("Aggregation pipeline must be an array");
}
return (new Mingo.Aggregator(pipeline)).run(collection);
};
/**
* Add new operators
* @param type the operator type to extend
* @param f a function returning an object of new operators
*/
Mingo.addOperators = function (type, f) {
var newOperators = f({
resolve: resolve,
computeValue: computeValue,
ops: ops,
key: function () {
return settings.key;
}
});
// ensure correct type specified
if (!_.contains([OP_AGGREGATE, OP_GROUP, OP_PIPELINE, OP_PROJECTION, OP_QUERY], type)) {
throw new Error("Could not identify type '" + type + "'");
}
var operators = ops(type);
// check for existing operators
_.each(_.keys(newOperators), function (op) {
if (!/^\$\w+$/.test(op)) {
throw new Error("Invalid operator name '" + op + "'");
}
if (_.contains(operators, op)) {
throw new Error("Operator " + op + " is already defined for " + type + " operators");
}
});
var wrapped = {};
switch (type) {
case OP_QUERY:
_.each(_.keys(newOperators), function (op) {
wrapped[op] = (function (f, ctx) {
return function (selector, value) {
return {
test: function (obj) {
// value of field must be fully resolved.
var lhs = resolve(obj, selector);
var result = f.call(ctx, selector, lhs, value);
if (_.isBoolean(result)) {
return result;
} else if (result instanceof Mingo.Query) {
return result.test(obj);
} else {
throw new Error("Invalid return type for '" + op + "'. Must return a Boolean or Mingo.Query");
}
}
};
}
}(newOperators[op], newOperators));
});
break;
case OP_PROJECTION:
_.each(_.keys(newOperators), function (op) {
wrapped[op] = (function (f, ctx) {
return function (obj, expr, selector) {
var lhs = resolve(obj, selector);
return f.call(ctx, selector, lhs, expr);
}
}(newOperators[op], newOperators));
});
break;
default:
_.each(_.keys(newOperators), function (op) {
wrapped[op] = (function (f, ctx) {
return function () {
var args = Array.prototype.slice.call(arguments);
return f.apply(ctx, args);
}
}(newOperators[op], newOperators));
});
}
// toss the operator salad :)
_.extend(OPERATORS[type], wrapped);
};
/**
* Mixin for Backbone.Collection objects
*/
Mingo.CollectionMixin = {
/**
* Runs a query and returns a cursor to the result
* @param criteria
* @param projection
* @returns {Mingo.Cursor}
*/
query: function (criteria, projection) {
return Mingo.find(this.toJSON(), criteria, projection);
},
/**
* Runs the given aggregation operators on this collection
* @params pipeline
* @returns {Array}
*/
aggregate: function (pipeline) {
var args = [this.toJSON(), pipeline];
return Mingo.aggregate.apply(null, args);
}
};
var pipelineOperators = {
/**
* Groups documents together for the purpose of calculating aggregate values based on a collection of documents.
*
* @param collection
* @param expr
* @returns {Array}
*/
$group: function (collection, expr) {
// lookup key for grouping
var idKey = expr[settings.key];
var partitions = groupBy(collection, function (obj) {
return computeValue(obj, idKey, idKey);
});
var result = [];
// remove the group key
expr = _.omit(expr, settings.key);
_.each(partitions.keys, function (value, i) {
var obj = {};
// exclude undefined key value
if (!_.isUndefined(value)) {
obj[settings.key] = value;
}
// compute remaining keys in expression
for (var key in expr) {
if (expr.hasOwnProperty(key)) {
obj[key] = accumulate(partitions.groups[i], key, expr[key]);
}
}
result.push(obj);
});
return result;
},
/**
* Filters the document stream, and only allows matching documents to pass into the next pipeline stage.
* $match uses standard MongoDB queries.
*
* @param collection
* @param expr
* @returns {Array|*}
*/
$match: function (collection, expr) {
return (new Mingo.Query(expr)).find(collection).all();
},
/**
* Reshapes a document stream.
* $project can rename, add, or remove fields as well as create computed values and sub-documents.
*
* @param collection
* @param expr
* @returns {Array}
*/
$project: function (collection, expr) {
if (_.isEmpty(expr)) {
return collection;
}
var usesExclusion = false;
_.each(expr, function(val, key) {
if(val === 0 && key !== settings.key) {
usesExclusion = true;
}
if(val !== 0 && usesExclusion) {
throw new Error("You cannot mix including and excluding fields.");
}
});
// result collection
var projected = [];
var objKeys = _.keys(expr);
var idOnlyExcludedExpression = false;
if (_.contains(objKeys, settings.key)) {
var id = expr[settings.key];
if (id === 0 || id === false) {
objKeys = _.without(objKeys, settings.key);
if (_.isEmpty(objKeys)) {
idOnlyExcludedExpression = true;
}
}
} else {
// if not specified the add the ID field
objKeys.push(settings.key);
}
for (var i = 0; i < collection.length; i++) {
var obj = collection[i];
var cloneObj = {};
var foundSlice = false;
var foundExclusion = false;
var dropKeys = [];
if (idOnlyExcludedExpression) {
dropKeys.push(settings.key);
}
_.each(objKeys, function (key) {
var subExpr = expr[key];
var newValue;
if (key !== settings.key && subExpr === 0) {
foundExclusion = true;
}
// tiny optimization here to skip over id
if (key === settings.key && _.isEmpty(subExpr)) {
newValue = obj[key];
} else if (_.isString(subExpr)) {
newValue = computeValue(obj, subExpr, key);
} else if (subExpr === 1 || subExpr === true) {
newValue = _.result(obj, key);
} else if (_.isObject(subExpr)) {
var operator = _.keys(subExpr);
operator = operator.length > 1 ? false : operator[0];
if (operator !== false && _.contains(ops(OP_PROJECTION), operator)) {
// apply the projection operator on the operator expression for the key
var temp = projectionOperators[operator](obj, subExpr[operator], key);
if (!_.isUndefined(temp)) {
newValue = temp;
}
if (operator == '$slice') {
foundSlice = true;
}
} else {
// compute the value for the sub expression for the key
newValue = computeValue(obj, subExpr, key);
}
} else {
dropKeys.push(key);
}
if (!_.isUndefined(newValue)) {
cloneObj[key] = newValue;
}
});
// if projection included $slice operator
// Also if exclusion fields are found or we want to exclude only the id field
// include keys that were not explicitly excluded
if (foundSlice || foundExclusion || idOnlyExcludedExpression) {
cloneObj = _.defaults(cloneObj, _.omit(obj, dropKeys));
}
projected.push(cloneObj);
}
return projected;
},
/**
* Restricts the number of documents in an aggregation pipeline.
*
* @param collection
* @param value
* @returns {Object|*}
*/
$limit: function (collection, value) {
return _.first(collection, value);
},
/**
* Skips over a specified number of documents from the pipeline and returns the rest.
*
* @param collection
* @param value
* @returns {*}
*/
$skip: function (collection, value) {
return _.rest(collection, value);
},
/**
* Takes an array of documents and returns them as a stream of documents.
*
* @param collection
* @param expr
* @returns {Array}
*/
$unwind: function (collection, expr) {
var result = [];
var field = expr.substr(1);
for (var i = 0; i < collection.length; i++) {
var obj = collection[i];
// must throw an error if value is not an array
var value = getValue(obj, field);
if (_.isArray(value)) {
_.each(value, function (item) {
var tmp = _.clone(obj);
tmp[field] = item;
result.push(tmp);
});
} else {
throw new Error("Target field '" + field + "' is not of type Array.");
}
}
return result;
},
/**
* Takes all input documents and returns them in a stream of sorted documents.
*
* @param collection
* @param sortKeys
* @returns {*}
*/
$sort: function (collection, sortKeys) {
if (!_.isEmpty(sortKeys) && _.isObject(sortKeys)) {
var modifiers = _.keys(sortKeys);
modifiers.reverse().forEach(function (key) {
var indexes = [];
var grouped = _.groupBy(collection, function (obj) {
var value = resolve(obj, key);
indexes.push(value);
return value;
});
indexes = _.sortBy(_.uniq(indexes), function (item) {
return item;
});
if (sortKeys[key] === -1) {
indexes.reverse();
}
collection = [];
_.each(indexes, function (item) {
Array.prototype.push.apply(collection, grouped[item]);
});
});
}
return collection;
}
};
////////// QUERY OPERATORS //////////
var queryOperators = {};
var compoundOperators = {
/**
* Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
*
* @param selector
* @param value
* @returns {{test: Function}}
*/
$and: function (selector, value) {
if (!_.isArray(value)) {
throw new Error("Invalid expression for $and criteria");
}
var queries = [];
_.each(value, function (expr) {
queries.push(new Mingo.Query(expr));
});
return {
test: function (obj) {
for (var i = 0; i < queries.length; i++) {
if (!queries[i].test(obj)) {
return false;
}
}
return true;
}
};
},
/**
* Joins query clauses with a logical OR returns all documents that match the conditions of either clause.
*
* @param selector
* @param value
* @returns {{test: Function}}
*/
$or: function (selector, value) {
if (!_.isArray(value)) {
throw new Error("Invalid expression for $or criteria");
}
var queries = [];
_.each(value, function (expr) {
queries.push(new Mingo.Query(expr));
});
return {
test: function (obj) {
for (var i = 0; i < queries.length; i++) {
if (queries[i].test(obj)) {
return true;
}
}
return false;
}
};
},
/**
* Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
*
* @param selector
* @param value
* @returns {{test: Function}}
*/
$nor: function (selector, value) {
if (!_.isArray(value)) {
throw new Error("Invalid expression for $nor criteria");
}
var query = this.$or("$or", value);
return {
test: function (obj) {
return !query.test(obj);
}
};
},
/**
* Inverts the effect of a query expression and returns documents that do not match the query expression.
*
* @param selector
* @param value
* @returns {{test: Function}}
*/
$not: function (selector, value) {
var criteria = {};
criteria[selector] = normalize(value);
var query = new Mingo.Query(criteria);
return {
test: function (obj) {
return !query.test(obj);
}
};
},
/**
* Matches documents that satisfy a JavaScript expression.
*
* @param selector
* @param value
* @returns {{test: test}}
*/
$where: function (selector, value) {
if (!_.isFunction(value)) {
value = new Function("return " + value + ";");
}