Collection class that handles documents of same type

Implements

SylvieEventEmitter

Param

collection name

Param

(optional) array of property names to be indicized OR a configuration object

Param

array of property names to define unique constraints for

Param

array of property names to define exact constraints for

Param

array property names to define binary indexes for

Param

collection indices will be actively rebuilt rather than lazily

Param

whether listeners are invoked asynchronously

Param

set to true to disable meta property on documents

Param

set to false to enable Changes API

Param

set to false to enable Delta Changes API (requires Changes API, forces cloning)

Param

use Object.observe to update objects automatically

Param

specify whether inserts and queries clone to/from user

Param

converts date values on binary indexed properties to epoch time

Param

when false all docs are frozen

Param

'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign'

Param

age of document (in ms.) before document is considered aged/stale.

Param

time interval for clearing out 'aged' documents; not set by default.

See

Sylvie#addCollection for normal creation of collections

Type Parameters

Hierarchy

Constructors

Properties

Methods

Constructors

Properties

DynamicViews: DynamicView<ColT>[]
adaptiveBinaryIndices: boolean
addListener: (<F>(eventName: string | string[], listener: F) => F) = ...

Type declaration

    • <F>(eventName: string | string[], listener: F): F
    • Alias of LokiEventEmitter.prototype.on addListener(eventName, listener) - adds a listener to the queue of callbacks associated to an event

      Returns

      the index of the callback in the array of listeners for a particular event

      Memberof

      LokiEventEmitter

      Type Parameters

      • F extends ((...args: any[]) => any)

      Parameters

      • eventName: string | string[]

        the name(s) of the event(s) to listen to

      • listener: F

        callback function of listener to attach

      Returns F

asyncListeners: boolean = false

Prop

boolean determines whether or not the callbacks associated with each event should happen in an async fashion or not Default is false, which means events are synchronous

Memberof

LokiEventEmitter

autoupdate: boolean
binaryIndices: CollectionBinaryIndex
cachedBinaryIndex: CollectionBinaryIndex
cachedData: ColT[]
cachedDirtyIds: number[]
cachedIndex: number[]
changes: ChangeOps[]
cloneMethod: CloneMethods
cloneObjects: boolean
commitLog: {
    data: string;
    message: string;
    timestamp: number;
}[] = []

a collection of objects recording the changes applied through a commmitStage

constraints: {
    exact: Record<string, ExactIndex<number>>;
    unique: Record<string, UniqueIndex>;
}

Type declaration

data: ColT[]
dirty: boolean
dirtyIds: number[]
disableChangesApi: boolean
disableDeltaChangesApi: boolean
disableFreeze: boolean
disableMeta: boolean
events: {
    [eventName: string]: ((...args: any[]) => any)[];
} = {}

Prop

a hashmap, with each property being an array of callbacks

Memberof

LokiEventEmitter

Type declaration

  • [eventName: string]: ((...args: any[]) => any)[]
flushChanges: (() => void)

Type declaration

    • (): void
    • Returns void

getChangeDelta: ((obj: any, old: any) => any)

Type declaration

    • (obj: any, old: any): any
    • Parameters

      • obj: any
      • old: any

      Returns any

getChanges: (() => any)

Type declaration

    • (): any
    • Returns any

getObjectDelta: ((oldObject: any, newObject: any) => any)

Type declaration

    • (oldObject: any, newObject: any): any
    • Parameters

      • oldObject: any
      • newObject: any

      Returns any

idIndex: number[]
isIncremental: boolean
lokiConsoleWrapper: {
    error(message: string): void;
    log(message: string): void;
    warn(message: string): void;
} = ...

Type declaration

maxId: number
name: string
no_op: (() => void)

Type declaration

    • (): void
    • Returns void

objType: string
observerCallback: ((changes: any) => void)

Type declaration

    • (changes: any): void
    • Parameters

      • changes: any

      Returns void

save: any
serializableIndices: boolean
setChangesApi: ((enabled: any) => void)

Type declaration

    • (enabled: any): void
    • Parameters

      • enabled: any

      Returns void

stages: Record<string, CollectionDocument> = {}

stages: a map of uniquely identified 'stages', which hold copies of objects to be manipulated without affecting the data in the original collection

transactional: boolean
transforms: Record<string, (Record<string, any> & {
    type: string;
})[]>
ttl: {
    age?: number;
    daemon?: Timer;
    ttlInterval?: number;
}

Type declaration

  • Optional age?: number
  • Optional daemon?: Timer
  • Optional ttlInterval?: number
uniqueNames: string[]

Methods

  • Adaptively insert a selected item to the index.

    Parameters

    • dataPosition: number

      : coll.data array index/position

    • binaryIndexName: string

      : index to search for dataPosition in

    Returns void

  • Adaptively remove a selected item from the index.

    Parameters

    • dataPosition: number | number[]

      : coll.data array index/position

    • binaryIndexName: string

      : index to search for dataPosition in

    • Optional removedFromIndexOnly: boolean

    Returns any

  • Adaptively update a selected item within an index.

    Parameters

    • dataPosition: number

      : coll.data array index/position

    • binaryIndexName: string

      : index to search for dataPosition in

    Returns void

  • Add a dynamic view to the collection

    Returns

    reference to the dynamic view added

    Example

    var pview = users.addDynamicView('progeny');
    pview.applyFind({'age': {'$lte': 40}});
    pview.applySimpleSort('name');

    var results = pview.data();

    Parameters

    • Optional name: string

      name of dynamic view to add

    • Optional options: Partial<DynamicViewOptions>

      options to configure dynamic view with

    Returns any

  • Adds a named collection transform to the collection

    Example

    users.addTransform('progeny', [
    {
    type: 'find',
    value: {
    'age': {'$lte': 40}
    }
    }
    ]);

    var results = users.chain('progeny').data();

    Parameters

    • name: string

      name to associate with transform

    • transform: (Record<string, any> & {
          type: string;
      })[]

      an array of transformation 'step' objects to save into the collection

    Returns void

  • Parameters

    • fun: (() => void)
        • (): void
        • Returns void

    • callback: (() => void)
        • (): void
        • Returns void

    Returns void

  • Calculates the average numerical value of a property

    Returns

    average of property in all docs in the collection

    Parameters

    • field: any

      name of property in docs to average

    Returns number

  • Retrieve doc by Unique index

    Returns

    document matching the value passed

    Parameters

    • field: string

      name of uniquely indexed property to use when doing lookup

    • Optional value: string

      unique value to search for

    Returns any

  • Parameters

    • template: Record<string, any>

    Returns {
        $and: any[];
    }

    • $and: any[]
  • calculateRange() - Binary Search utility method to find range/segment of values matching criteria. this is used for collection.find() and first find filter of resultset/dynview slightly different than get() binary search in that get() hones in on 1 value, but we have to hone in on many (range)

    Returns

    [start, end] index array positions

    Parameters

    • op: string

      operation, such as $eq

    • prop: string

      name of property to calculate range for

    • val: any

      value to use for range calculation.

    Returns [start: number, end: number]

  • Internal method used for indexed $between. Given a prop (index name), and a value (which may or may not yet exist) this will find the final position of that upper range value.

    Parameters

    • prop: string
    • val: any
    • usingDotNotation: boolean

    Returns number

  • Internal method used for index maintenance and indexed searching. Calculates the beginning of an index range for a given value. For index maintainance (adaptive:true), we will return a valid index position to insert to. For querying (adaptive:false/undefined), we will : return lower bound/index of range of that value (if found) return next lower index position if not found (hole) If index is empty it is assumed to be handled at higher level, so this method assumes there is at least 1 document in index.

    Parameters

    • prop: string

      name of property which has binary index

    • val: any

      value to find within index

    • adaptive: boolean

      if true, we will return insert position

    • Optional usingDotNotation: boolean

    Returns number

  • Chain method, used for beginning a series of chained find() and/or view() operations on a collection.

    Returns

    (this) resultset, or data array if any map or join functions where called

    Parameters

    • Optional transform: ChainTransform

      named transform or array of transform steps

    • Optional parameters: any

      Object containing properties representing parameters to substitute

    Returns any

  • Perform checks to determine validity/consistency of all binary indices

    Returns

    array of index names where problems were found.

    Example

    // check all indices on a collection, returns array of invalid index names
    var result = coll.checkAllIndexes({ repair: true, randomSampling: true, randomSamplingFactor: 0.15 });
    if (result.length > 0) {
    results.forEach(function(name) {
    console.log('problem encountered with index : ' + name);
    });
    }

    Parameters

    • Optional options: {
          randomSampling: boolean;
          randomSamplingFactor: number;
          repair: boolean;
      }

      optional configuration object

      • randomSampling: boolean

        whether (faster) random sampling should be used

      • randomSamplingFactor: number

        percentage of total rows to randomly sample

      • repair: boolean

        whether to fix problems if they are encountered

    Returns string[]

  • Perform checks to determine validity/consistency of a binary index

    Returns

    whether the index was found to be valid (before optional correcting).

    Example

    // full test
    var valid = coll.checkIndex('name');
    // full test with repair (if issues found)
    valid = coll.checkIndex('name', { repair: true });
    // random sampling (default is 10% of total document count)
    valid = coll.checkIndex('name', { randomSampling: true });
    // random sampling (sample 20% of total document count)
    valid = coll.checkIndex('name', { randomSampling: true, randomSamplingFactor: 0.20 });
    // random sampling (implied boolean)
    valid = coll.checkIndex('name', { randomSamplingFactor: 0.20 });
    // random sampling with repair (if issues found)
    valid = coll.checkIndex('name', { repair: true, randomSampling: true });

    Parameters

    • property: string

      name of the binary-indexed property to check

    • options: {
          randomSampling?: boolean;
          randomSamplingFactor?: number;
          repair?: boolean;
      } = {}

      optional configuration object

      • Optional randomSampling?: boolean

        whether (faster) random sampling should be used

      • Optional randomSamplingFactor?: number

        percentage of total rows to randomly sample

      • Optional repair?: boolean

        whether to fix problems if they are encountered

    Returns boolean

  • Empties the collection of all data but leaves indexes and options intact by default.

    Parameters

    • Optional options: {
          removeIndices?: boolean;
      }

      configure clear behavior

      • Optional removeIndices?: boolean

        whether to remove indices in addition to data

    Returns void

  • (Staging API) re-attach all objects to the original collection, so indexes and views can be rebuilt then create a message to be inserted in the commitlog

    Parameters

    • stageName: string

      name of stage

    • message: string

    Returns void

  • Will allow reconfiguring certain collection options.

    Parameters

    • options: {
          adaptiveBinaryIndices?: boolean;
      } = {}
      • Optional adaptiveBinaryIndices?: boolean

        collection indices will be actively rebuilt rather than lazily

    Returns void

  • Quickly determine number of documents in collection (or query)

    Returns

    number of documents in the collection

    Parameters

    • Optional query: Record<string, any>

      (optional) query object to count results of

    Returns number

  • emit(eventName, data) - emits a particular event with the option of passing optional parameters which are going to be processed by the callback provided signatures match (i.e. if passing emit(event, arg0, arg1) the listener should take two parameters)

    Memberof

    LokiEventEmitter

    Parameters

    • eventName: string

      the name of the event

    • Optional data: unknown

      optional object passed with the event

    • Optional arg: any

    Returns void

  • Ensure all binary indices

    Parameters

    • Optional force: boolean

      whether to force rebuild of existing lazy binary indices

    Returns void

  • Rebuild idIndex async with callback - useful for background syncing with a remote server

    Parameters

    • callback: any

    Returns void

  • Ensure binary index on a certain field

    Parameters

    • property: string

      name of property to create binary index on

    • Optional force: boolean

      (Optional) flag indicating whether to construct index immediately

    Returns void

  • Join two collections on specified properties

    Returns

    Result of the mapping operation

    Parameters

    • joinData: Collection<ColT> | ColT[] | ResultSet<ColT>

      array of documents to 'join' to this collection

    • leftJoinProp: string

      property name in collection

    • rightJoinProp: string

      property name in joinData

    • mapFun: (() => void)

      (Optional) map function to use

        • (): void
        • Returns void

    • dataOptions: {
          forceCloneMethod: CloneMethods;
          forceClones: boolean;
          removeMeta: boolean;
      }

      options to data() before input to your map function

      • forceCloneMethod: CloneMethods

        Allows overriding the default or collection specified cloning method.

      • forceClones: boolean

        forcing the return of cloned objects to your map object

      • removeMeta: boolean

        allows removing meta before calling mapFun

    Returns ResultSet<ColT>

  • Find method, api is similar to mongodb. for more complex queries use [chain()]chain or [where()]where.

    Example

    {@tutorial Query Examples}
    

    Returns

    Array of matching documents

    Parameters

    • Optional query: Record<string, any>

      'mongo-like' query object

    Returns ColT[]

  • Applies a 'mongo-like' find query object removes all documents which match that filter.

    Parameters

    • Optional filterObject: Record<string, any>

      'mongo-like' query object

    Returns void

  • Applies a 'mongo-like' find query object and passes all results to an update function. For filter function querying you should migrate to [updateWhere()]updateWhere.

    Parameters

    • filterObject: any

      'mongo-like' query object (or deprecated filterFunction mode)

    • updateFunction: any

      update function to run against filtered documents

    Returns void

  • Find one object by index property, by property equal to value

    Returns

    First matching document, or null if none

    Parameters

    • query: {} = {}

      query object used to perform search with

      Returns ColT

    • Find object by unindexed field by property equal to value, simply iterates and returns the first element matching the query

      Parameters

      • prop: any
      • value: any

      Returns any

    • Get by Id - faster than other methods because of the searching algorithm

      Returns

      Object reference if document was found, null if not, or an array if 'returnPosition' was passed.

      Parameters

      • id: number

        $loki id of document you want to retrieve

      • Optional returnPosition: boolean

        if 'true' we will return [object, position]

      Returns object | any[]

    • Perform binary range lookup for the data[dataPosition][binaryIndexName] property value Since multiple documents may contain the same value (which the index is sorted on), we hone in on range and then linear scan range to find exact index array position.

      Parameters

      • dataPosition: number

        : coll.data array index/position

      • binaryIndexName: string

        : index to search for dataPosition in

      Returns number

    • Retrieves a named transform from the collection.

      Parameters

      • name: string

        name of the transform to lookup.

      Returns (Record<string, any> & {
          type: string;
      })[]

    • Adds object(s) to collection, ensure object(s) have meta properties, clone it if necessary, etc.

      Returns

      document or documents inserted

      Example

      users.insert({
      name: 'Odin',
      age: 50,
      address: 'Asgard'
      });

      // alternatively, insert array of documents
      users.insert([{ name: 'Thor', age: 35}, { name: 'Loki', age: 30}]);

      Type Parameters

      Parameters

      • doc: T

        the document (or array of documents) to be inserted

      • Optional overrideAdaptiveIndices: boolean

        (optional) if true, adaptive indicies will be temporarily disabled and then fully rebuilt after batch. This will be faster for large inserts, but slower for small/medium inserts in large collections

      Returns T

    • Adds a single object, ensures it has meta properties, clone it if necessary, etc.

      Returns

      document or 'undefined' if there was a problem inserting it

      Type Parameters

      Parameters

      • doc: T

        the document to be inserted

      • Optional bulkInsert: boolean

        quiet pre-insert and insert event emits

      Returns T

    • Map Reduce operation

      Returns

      The result of your mapReduce operation

      Parameters

      • mapFunction: any

        function to use as map function

      • reduceFunction: any

        function to use as reduce function

      Returns any

    • Parameters

      • field: any

      Returns {
          index: number;
          value: any;
      }

      • index: number
      • value: any
    • Parameters

      • field: any

      Returns {
          index: number;
          value: any;
      }

      • index: number
      • value: any
    • on(eventName, listener) - adds a listener to the queue of callbacks associated to an event

      Returns

      the index of the callback in the array of listeners for a particular event

      Memberof

      LokiEventEmitter

      Type Parameters

      • F extends ((...args: any[]) => any)

      Parameters

      • eventName: string | string[]

        the name(s) of the event(s) to listen to

      • listener: F

        callback function of listener to attach

      Returns F

    • Internal method to remove a batch of documents from the collection.

      Parameters

      • positions: number[]

        data/idIndex positions to remove

      Returns any

    • removeListener() - removes the listener at position 'index' from the event 'eventName'

      Memberof

      LokiEventEmitter

      Parameters

      • eventName: string | string[]

        the name(s) of the event(s) which the listener is attached to

      • listener: ((...args: any[]) => any)

        the listener callback function to remove from emitter

          • (...args: any[]): any
          • Parameters

            • Rest ...args: any[]

            Returns any

      Returns void

    • Removes a named collection transform from the collection

      Parameters

      • name: string

        name of collection transform to remove

      Returns void

    • Remove all documents matching supplied filter function. For 'mongo-like' querying you should migrate to [findAndRemove()]findAndRemove.

      Parameters

      • query: Record<string, any> | ((...args: any[]) => any)

        query object to filter on

      Returns void

    • Updates or applies collection TTL settings.

      Parameters

      • age: number

        age (in ms) to expire document from collection

      • interval: number

        time (in ms) to clear collection of aged documents.

      Returns void

    • Updates a named collection transform to the collection

      Parameters

      • name: string

        name to associate with transform

      • transform: (Record<string, any> & {
            type: string;
        })[]

        a transformation object to save into collection

      Returns void

    • Applies a filter function and passes all results to an update function.

      Parameters

      • filterFunction: any

        filter function whose results will execute update

      • updateFunction: any

        update function to run against filtered documents

      Returns void

    • Query the collection by supplying a javascript filter function.

      Example

      var results = coll.where(function(obj) {
      return obj.legs === 8;
      });

      Returns

      all documents which pass your filter function

      Parameters

      • fun: any

        filter function to run against all collection docs

      Returns ColT[]

    Generated using TypeDoc