qualia:mapped-collection

v0.0.1Published 7 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

qualia:mapped-collection

Maintain a projection of a MongoDB collection in memory on your Meteor server, for awesome possibilities!

Usage

Let's say we have a collection of Orders and we want to search through them, but MongoDB queries aren't quite expressive enough.

We only need to search over a small subset of the fields on each document. With MappedCollection, we can project each order into an ES6 Map in memory, then run an arbitrary search algorithm on the map using normal JavaScript!

First, we create the MappedCollection, specifying the collection we would like to map into memory, and which fields we should project from each document:

1import {MappedCollection} from 'meteor/qualia:mapped-collection';
2
3const mappedFields = [
4  'order_number',
5  '_search.borrower_names',
6  '_search.seller_names',
7  '_search.lender_names',
8  '_search.property_addresses',
9  'properties.brief_legal_description',
10  'cdf.loans.loan_number',
11  'hud1.loans.loan_number',
12  'status',
13];
14
15const mappedOrders = new MappedCollection({
16  collection: Orders,
17  fields: mappedFields,
18});

Provide an array of field names or a Meteor-style fields object in fields.

Internally, MappedCollection uses an observe to keep its map in sync with the collection.

After we construct mappedOrders, it might still be waiting to build the map asynchronously. When our mappedOrders are ready, the Promise mappedOrders.ready will resolve.

The map is available on the MappedCollection as map, and we use it to get the values for our search once the map is ready:

1import lasr from 'meteor/qualia:lasr';
2
3// mappedOrders.ready resolves when the map is fully initialized
4Promise.await(mappedOrders.ready);
5
6// mappedOrders.map is a normal ES6 Map
7const orders = Array.from(mappedOrders.map.values());
8
9// Here, we search for some orders, but you can do anything with the map!
10const results = lasr.search({
11  items: orders,
12  query,
13  keys: ['order_number'],
14  limit: 10,
15});

Here, we use lasr for our search, but you could use any search package, or do something unrelated to search!