Skip to main content

Collection <T>

Collection class that handles documents of same type

@param

collection name

@param

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

@see

addCollection for normal creation of collections

Hierarchy

Index

Constructors

constructor

  • Type parameters

    • T

    Parameters

    Returns Collection<T>

Properties

adaptiveBinaryIndices

adaptiveBinaryIndices: boolean

if set to true we will optimally keep indices ‘fresh’ during insert/update/remove ops (never dirty/never needs rebuild) if you frequently intersperse insert/update/remove ops between find ops this will likely be significantly faster option.

asyncListeners

asyncListeners: boolean

option to make event listeners async, default is sync

autoupdate

autoupdate: boolean

option to observe objects and update them automatically, ignored if Object.observe is not supported

binaryIndices

binaryIndices: Record<ValidSimpleLensField, IBinaryIndex<number>> = ...

user defined indexes, this field supports dot notation

changes

changes: ICollectionChange<T>[] = []

changes are tracked by collection and aggregated by the db

cloneMethod

cloneMethod: CloneMethod

default clone method (if enabled) is parse-stringify

cloneObjects

cloneObjects: boolean

options to clone objects when inserting them

commitLog

commitLog: ICollectionCommitLog<T>[] = []

a collection of objects recording the changes applied through a commit stage

constraints

constraints: { exact: Record<string, ExactIndex<string>>; unique: any } = ...

Type declaration

  • exact: Record<string, ExactIndex<string>>
  • unique: any

createStack

createStack: string = ...

createTime

createTime: number = ...

data

data: (T & ICollectionDocument)[] = []

the data held by the collection

dirty

dirty: boolean = true

in autosave scenarios we will use collection level dirty flags to determine whether save is needed. Currently, if any collection is dirty we will autosave the whole database if autosave is configured. defaulting to true since this is called from addCollection and adding a collection should trigger save.

disableChangesApi

disableChangesApi: boolean

disable track changes

disableDeltaChangesApi

disableDeltaChangesApi: boolean

disable delta update object style on changes

readonlydisableFreeze

disableFreeze: boolean

option to deep freeze all documents

readonlydisableMeta

disableMeta: boolean

if set to true we will not maintain a meta property for a document

dynamicViews

dynamicViews: DynamicView<T>[] = []

fire

fire: <T>(event: Event<EventDetail<T>>) => boolean = ...

Type declaration

idIndex

idIndex: number[] = null

position-&gt;$loki index (built lazily)

isIncremental

isIncremental: boolean = false

maxId

maxId: number = 0

currentMaxId - change manually at your own peril!

publicname

name: string = 'Collection'

objType

objType: string

the object type of the collection

off

off: <T>(type: EventName<T>, callback: Listener<T>, options?: boolean | EventListenerOptions) => void = ...

Type declaration

on

on: <T>(type: T, listener: Listener<T>, options?: boolean | AddEventListenerOptions) => void = ...

Type declaration

options

options: ICollectionOptions<T>

sd

sd: <K>(field: K) => number = ...

Type declaration

    • <K>(field: K): number
    • Type parameters

      • K: string | number | symbol

      Parameters

      • field: K

      Returns number

readonlyserializableIndices

serializableIndices: boolean

by default, if you insert a document into a collection with binary indices, if those indexed properties contain a DateTime we will convert to epoch time format so that (across serializations) its value position will be the same ‘after’ serialization as it was ‘before’.

stages

stages: Record<string, Record<number, T & ICollectionDocument>> = ...

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

transactional

transactional: boolean

is collection transactional

transforms

transforms: Record<string, TransformRequest<T, any, any>[]> = {}

transforms will be used to store frequently used query chains as a series of steps which itself can be stored along with the database.

readonlyttl

ttl: ITtlStatus = ...

option to activate a cleaner daemon - clears ‘aged’ documents at set intervals.

uniqueNames

uniqueNames: ValidSimpleLensField[] = []

unique constraints contain duplicate object references, so they are not persisted. we will keep track of properties which have unique constraint applied here, and regenerate lazily.

Methods

adaptiveBinaryIndexInsert

  • adaptiveBinaryIndexInsert<K, D>(dataPosition: number, binaryIndexName: K, usingDotNotation?: D): void
  • Adaptively insert a selected item to the index.


    Type parameters

    Parameters

    • dataPosition: number

      : coll.data array index/position

    • binaryIndexName: K

      : index to search for dataPosition in

    • optionalusingDotNotation: D

    Returns void

adaptiveBinaryIndexRemove

  • adaptiveBinaryIndexRemove(dataPosition: number | number[], binaryIndexName: keyof T, removedFromIndexOnly?: boolean): any
  • Adaptively remove a selected item from the index.


    Parameters

    • dataPosition: number | number[]

      coll.data array index/position

    • binaryIndexName: keyof T

      index to search for dataPosition in

    • optionalremovedFromIndexOnly: boolean

    Returns any

adaptiveBinaryIndexUpdate

  • Adaptively update a selected item within an index.


    Parameters

    • dataPosition: number

      coll.data array index/position

    • binaryIndexName: ValidSimpleLensField

      index to search for dataPosition in

    Returns void

add

  • add(document: T): any
  • Add object to collection


    Parameters

    • document: T

    Returns any

addAutoUpdateObserver

addDynamicView

  • addDynamicView(name?: string, options?: Partial<IDynamicViewOptions>): DynamicView<T>
  • Add a dynamic view to the collection

    @example
    const progenyView = users.addDynamicView('progeny');
    progenyView.applyFind({'age': {'$lte': 40}});
    progenyView.applySimpleSort('name');

    const results = progenyView.data();

    Parameters

    • name: string = ''

      name of dynamic view to add

    • optionaloptions: Partial<IDynamicViewOptions>

      options to configure dynamic view with

    Returns DynamicView<T>

addEventListener

  • addEventListener<T>(type: T, listener: Listener<T>, options?: boolean | AddEventListenerOptions): void
  • Type parameters

    • T: EventName<any, T>

    Parameters

    • type: T
    • listener: Listener<T>
    • optionaloptions: boolean | AddEventListenerOptions

    Returns void

addTransform

  • addTransform<R0, R1>(name: string, transform: TransformRequest<T, R0, R1>[]): void
  • Adds a named collection transform to the collection

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

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

    Type parameters

    • R0
    • R1

    Parameters

    • name: string

      name to associate with transform

    • transform: TransformRequest<T, R0, R1>[]

      an array of transformation ‘step’ objects to save into the collection

    Returns void

by

  • by<K>(field: K, value?: T[K]): any
  • Retrieve doc by Unique index


    Type parameters

    • K: string | number | symbol

    Parameters

    • field: K

      name of uniquely indexed property to use when doing lookup

    • optionalvalue: T[K]

      unique value to search for

    Returns any

    document matching the value passed

byExample

calculateRange

  • calculateRange<P, D>(operation: $size | $eq | $aeq | $ne | $dteq | $gt | $gte | $lt | $lte | $jgt | $jgte | $jlt | $jlte | $between | $jbetween | $in | $inSet | $nin | $keyin | $nkeyin | $definedin | $undefinedin | $regex | $containsString | $containsAny | $containsNone | $contains | $elemMatch | $type | $finite | $len | $where | $not | $exists, property: P, value: LensResult<T, P, D>, usingDotNotation?: D): [number, number]
  • 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/dynamicView slightly different than get() binary search in that get() hones in on 1 value, but we have to hone in on many (range)


    Type parameters

    Parameters

    • operation: $size | $eq | $aeq | $ne | $dteq | $gt | $gte | $lt | $lte | $jgt | $jgte | $jlt | $jlte | $between | $jbetween | $in | $inSet | $nin | $keyin | $nkeyin | $definedin | $undefinedin | $regex | $containsString | $containsAny | $containsNone | $contains | $elemMatch | $type | $finite | $len | $where | $not | $exists

      operation, such as $eq

    • property: P

      name of property to calculate range for

    • value: LensResult<T, P, D>

      value to use for range calculation.

    • optionalusingDotNotation: D

    Returns [number, number]

    [start, end] index array positions

calculateRangeStart

  • Internal method used for index maintenance and indexed searching. Calculates the beginning of an index range for a given value. For index maintenance (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.


    Type parameters

    Parameters

    • property: ValidSimpleLensField

      name of property which has binary index

    • value: LensResult<T, P, D>

      value to find within index

    • optionaladaptive: boolean

      if true, we will return insert position

    • optionalusingDotNotation: D

    Returns number

chain

  • chain(): ResultSet<T>
  • chain(transformId: string, parameters?: Record<string, unknown>): ResultSet<T>
  • chain<R0, R1, Transform>(transform: TransformRequest<T, R0, R1> | TransformRequest<T, R0, R1>[], parameters?: Record<string, unknown>): ResultSet<TransformResult<Transform>>
  • Chain method, used for beginning a series of chained find() and/or view() operations on a collection.


    Returns ResultSet<T>

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

checkAllIndexes

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

    @example
    // check all indices on a collection, returns array of invalid index names
    const 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

    Returns any[]

    array of index names where problems were found.

checkIndex

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

    @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: keyof T

      name of the binary-indexed property to check

    • optionaloptions: Partial<ICheckCollectionIndexOptions>

      optional configuration object

    • optionalusingDotNotation: boolean

    Returns boolean

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

clear

  • Empties the collection.


    Parameters

    Returns void

commitStage

  • commitStage(stageName: string, message: string): 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 commit log

    @memberof

    Collection


    Parameters

    • stageName: string

      name of stage

    • message: string

    Returns void

configureOptions

count

createChange

  • Parameters

    Returns void

createInsertChange

  • createInsertChange(object: T): void
  • Parameters

    • object: T

    Returns void

createUpdateChange

  • createUpdateChange(object: T, newObject: T): void
  • Parameters

    • object: T
    • newObject: T

    Returns void

dispatchEvent

  • dispatchEvent<T>(event: Event<EventDetail<T>>): boolean
  • Type parameters

    • T: EventName<any, T>

    Parameters

    • event: Event<EventDetail<T>>

    Returns boolean

ensureAllIndexes

  • ensureAllIndexes(force?: boolean): void
  • Ensure all binary indices


    Parameters

    • optionalforce: boolean

      whether to force rebuild of existing lazy binary indices

    Returns void

ensureId

  • ensureId(): void
  • Rebuild idIndex


    Returns void

ensureIdAsync

  • ensureIdAsync(): Promise<void>
  • Rebuild idIndex async with callback - useful for background syncing with a remote server


    Returns Promise<void>

ensureIndex

  • Ensure binary index on a certain field


    Parameters

    • property: ValidSimpleLensField

      name of property to create binary index on

    • optionalforce: boolean

      (Optional) flag indicating whether to construct index immediately

    Returns void

ensureUniqueIndex

  • ensureUniqueIndex<P>(field: P): UniqueIndex<T>

eqJoin

  • eqJoin<R>(joinData: Collection<R> | ResultSet<R> | R[], leftJoinKey: keyof T | JoinKeyFunction<T>, rightJoinKey: JoinKeyFunction<R> | keyof R): ResultSet<{ left: T; right: R }>
  • eqJoin<R>(joinData: R[] | Collection<R> | ResultSet<R>, leftJoinKey: keyof T | JoinKeyFunction<T>, rightJoinKey: keyof R | JoinKeyFunction<R>, mapFunction?: (left: T, right: R) => T): ResultSet<T>
  • eqJoin<R, R0>(joinData: R[] | Collection<R> | ResultSet<R>, leftJoinKey: keyof T | JoinKeyFunction<T>, rightJoinKey: keyof R | JoinKeyFunction<R>, mapFunction: (left: T, right: R) => R0): ResultSet<R0>
  • Join two collections on specified properties


    Type parameters

    • R: object

    Parameters

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

      array of documents to ‘join’ to this collection

    • leftJoinKey: keyof T | JoinKeyFunction<T>
    • rightJoinKey: JoinKeyFunction<R> | keyof R

    Returns ResultSet<{ left: T; right: R }>

    Result of the mapping operation

extract

extractNumerical

  • extractNumerical<K>(field: K): number[]
  • Type parameters

    • K: string | number | symbol

    Parameters

    • field: K

    Returns number[]

find

findAndRemove

findAndUpdate

findObject

findObjects

findOne

findOneUnIndexed

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


    Type parameters

    • K: string | number | symbol

    Parameters

    • property: K
    • value: T[K]

    Returns T & ICollectionDocument

flushChanges

  • flushChanges(): void
  • Returns void

get

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


    Parameters

    • id: number

      $loki id of document you want to retrieve

    • returnPosition: true

      if ‘true’ we will return [object, position]

    Returns [T & ICollectionDocument, number]

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

getBinaryIndexPosition

  • getBinaryIndexPosition<K, D>(dataPosition: number, binaryIndexName: K, usingDotNotation?: D): number
  • 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.


    Type parameters

    • K: string | number | symbol
    • D: boolean

    Parameters

    • dataPosition: number

      coll.data array index/position

    • binaryIndexName: K

      index to search for dataPosition in

    • optionalusingDotNotation: D

    Returns number

getBinaryIndexValues

getChangeDelta

  • getChangeDelta<P>(newObject: P, oldObject?: P): any
  • Compare changed object (which is a forced clone) with existing object and return the delta


    Type parameters

    • P

    Parameters

    • newObject: P
    • optionaloldObject: P

    Returns any

getChanges

getDynamicView

  • getDynamicView(name: string): DynamicView<T>
  • Look up dynamic view reference from within the collection


    Parameters

    • name: string

      name of dynamic view to retrieve reference of

    Returns DynamicView<T>

    A reference to the dynamic view with that name

getObjectDelta

  • getObjectDelta<P>(oldObject: P, newObject: P): P | Partial<T>
  • Type parameters

    • P

    Parameters

    • oldObject: P
    • newObject: P

    Returns P | Partial<T>

getStage

  • (Staging API) create a stage and/or retrieve it


    Parameters

    • name: string

    Returns Record<number, T & ICollectionDocument>

getTransform

  • getTransform(name: string): TransformRequest<T, any, any>[]
  • Retrieves a named transform from the collection.


    Parameters

    • name: string

      name of the transform to lookup.

    Returns TransformRequest<T, any, any>[]

getUniqueIndex

  • Returns a named unique index


    Parameters

    • field: ValidSimpleLensField

      indexed field name

    • optionalforce: boolean

      if true, will rebuild index; otherwise, function may return null

    Returns any

insert

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

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

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

    Parameters

    • documents: T

      the document (or array of documents) to be inserted

    • optionaloverrideAdaptiveIndices: boolean

      (optional) if true, adaptive indices 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 & ICollectionDocument

    document or documents inserted

insertMeta

  • insertMeta(object: T): void
  • Parameters

    • object: T

    Returns void

insertMetaWithChange

  • insertMetaWithChange(object: T): void
  • Parameters

    • object: T

    Returns void

insertOne

  • insertOne(document: T, bulkInsert?: boolean): any
  • Adds a single object, ensures it has meta properties, clone it if necessary, etc.


    Parameters

    • document: T

      the document to be inserted

    • optionalbulkInsert: boolean

      quiet pre-insert and insert event emits

    Returns any

    document or ‘undefined’ if there was a problem inserting it

mapReduce

  • mapReduce<P, U>(mapFunction: (x: T & ICollectionDocument) => P, reduceFunction: (x: P[]) => U): U
  • Map Reduce operation


    Type parameters

    • P
    • U

    Parameters

    • mapFunction: (x: T & ICollectionDocument) => P

      function to use as map function

    • reduceFunction: (x: P[]) => U

      function to use as reduce function

    Returns U

    The result of your mapReduce operation

max

  • max<K>(field: K): any
  • Type parameters

    • K: string | number | symbol

    Parameters

    • field: K

    Returns any

maxRecord

  • maxRecord<K>(field: K): { index: number; value: number }
  • Type parameters

    • K: string | number | symbol

    Parameters

    • field: K

    Returns { index: number; value: number }

    • index: number
    • value: number

mean

  • mean<K>(field: K): number
  • Calculates the average numerical value of a property


    Type parameters

    • K: string | number | symbol

    Parameters

    • field: K

      name of property in docs to average

    Returns number

    average of property in all docs in the collection

median

  • median<K>(field: K): number
  • Type parameters

    • K: string | number | symbol

    Parameters

    • field: K

    Returns number

min

  • min<K>(field: K): any
  • Type parameters

    • K: string | number | symbol

    Parameters

    • field: K

    Returns any

minRecord

  • minRecord<K>(field: K): { index: number; value: number }
  • Type parameters

    • K: string | number | symbol

    Parameters

    • field: K

    Returns { index: number; value: number }

    • index: number
    • value: number

mode

  • mode<K>(field: K): number
  • Type parameters

    • K: string | number | symbol

    Parameters

    • field: K

    Returns number

observerCallback

prepareFullDocIndex

  • prepareFullDocIndex(): number[]
  • create a row filter that covers all documents in the collection


    Returns number[]

remove

removeBatchByPositions

  • removeBatchByPositions(positions: number[]): any
  • Internal method to remove a batch of documents from the collection.


    Parameters

    • positions: number[]

      data/idIndex positions to remove

    Returns any

removeDataOnly

  • removeDataOnly(): void
  • Returns void

removeDynamicView

  • removeDynamicView(name: string): void
  • Remove a dynamic view from the collection


    Parameters

    • name: string

      name of dynamic view to remove

    Returns void

removeEventListener

  • removeEventListener<T>(type: EventName<T>, callback: Listener<T>, options?: boolean | EventListenerOptions): void
  • Type parameters

    • T: EventName<any, T>

    Parameters

    • type: EventName<T>
    • callback: Listener<T>
    • optionaloptions: boolean | EventListenerOptions

    Returns void

removeTransform

  • removeTransform(name: string): void
  • Removes a named collection transform from the collection


    Parameters

    • name: string

      name of collection transform to remove

    Returns void

removeWhere

rollback

  • rollback(): void
  • roll back the transaction


    Returns void

setChangesApi

  • setChangesApi(enabled: boolean): void
  • Parameters

    • enabled: boolean

    Returns void

setTTL

  • setTTL(age: number, interval: number): 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

setTransform

  • setTransform(name: string, transform: TransformRequest<T, T, T>[]): void
  • Updates a named collection transform to the collection


    Parameters

    • name: string

      name to associate with transform

    • transform: TransformRequest<T, T, T>[]

      a transformation object to save into collection

    Returns void

stage

  • (Staging API) create a copy of an object and insert it into a stage


    Parameters

    Returns any

standardDeviation

  • standardDeviation<K>(field: K): number
  • Type parameters

    • K: string | number | symbol

    Parameters

    • field: K

    Returns number

ttlDaemonFuncGen

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

      • (): void
      • Returns void

update

  • Updates an object and notifies collection that the document has changed.


    Parameters

    Returns any

updateMeta

  • updateMeta(object: T): T
  • Parameters

    • object: T

    Returns T

updateMetaWithChange

  • updateMetaWithChange(object: T, oldObject: T): T
  • Parameters

    • object: T
    • oldObject: T

    Returns T

updateWhere

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


    Parameters

    Returns void

where

  • Query the collection by supplying a javascript filter function.

    @example
    const results = collection.where(function(document) {
    return document.legs === 8;
    });

    Parameters

    • filter: FilterFunction<T>

      filter function to run against all collection docs

    Returns (T & ICollectionDocument)[]

    all documents which pass your filter function