-
Notifications
You must be signed in to change notification settings - Fork 1
/
filter-documents.ts
46 lines (43 loc) · 1.22 KB
/
filter-documents.ts
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
import * as Mingo from 'mingo';
/**
* FilterOptions
* FilterOptions can be used to customized how documents are filtered.
* All fields are optional and they are always used in this order:
* 1. sort
* 2. skip
* 3. limit
*/
export type FilterOptions = {
sort?: any;
limit?: number;
skip?: number;
};
/**
* createFilterFunction
* createFilterFunction creates a function which can be used to filter
* an array of documents. Converts mongodb like query objects to functions.
*
* @param filter: A mongodb like filter object.
*/
export const createFilterFunction = (filter: any): Function => {
const query = new Mingo.Query(filter);
return (doc: any) => query.test(doc);
};
/**
* filterDocuments
* filterDocuments returns a subset of documents using given filter options.
* The filter parameter is similar to the one used in Mongo database queries.
*/
export const filterDocuments = (filter: any, docs: any[], options: FilterOptions = {}): any[] => {
let cursor = Mingo.find(docs, filter);
if (options.sort) {
cursor = cursor.sort(options.sort);
}
if (options.skip) {
cursor = cursor.skip(options.skip);
}
if (options.limit) {
cursor = cursor.limit(options.limit);
}
return cursor.all();
};