Class: Collection

Collection


new Collection(records, opts)

import {Collection} from 'js-data'

An ordered set of Record instances.

Parameters:
Name Type Argument Description
records Array <optional>

Initial set of records to insert into the collection.

opts Object <optional>

Configuration options.

Properties
Name Type Argument Default Description
idAttribute string <optional>

See Collection#idAttribute.

onConflict string <optional>
"merge"

See Collection#onConflict.

mapper string <optional>

See Collection#mapper.

recordOpts Object <optional>
null

See Collection#recordOpts.

Source:
Example
import {Collection, Record} from 'js-data'
const user1 = new Record({ id: 1 })
const user2 = new Record({ id: 2 })
const UserCollection = new Collection([user1, user2])
UserCollection.get(1) === user1 // true

Members


idAttribute :string

Field to be used as the unique identifier for records in this collection. Defaults to "id" unless Collection#mapper is set, in which case this will default to Mapper#idAttribute.

Type:
  • string
Default Value:
  • "id"
Source:

index :Index

The main index, which uses @{link Collection#recordId} as the key.

Type:
  • Index
Source:

indexes :Object.<string, Index>

Object that holds the secondary indexes of this collection.

Type:
  • Object.<string, Index>
Source:

mapper :Mapper

Default Mapper for this collection. Optional. If a Mapper is provided, then the collection will use the Mapper#idAttribute setting, and will wrap records in Mapper#RecordClass.

Type:
Default Value:
  • null
Source:
Example
import {Collection, Mapper} from 'js-data'

class MyMapperClass extends Mapper {
  foo () { return 'bar' }
}
const myMapper = new MyMapperClass()
const collection = new Collection(null, { mapper: myMapper })

onConflict :string

What to do when inserting a record into this Collection that shares a primary key with a record already in this Collection.

Possible values:

  • merge
  • replace

Merge:

Recursively shallow copy properties from the new record onto the existing record.

Replace:

Shallow copy top-level properties from the new record onto the existing record. Any top-level own properties of the existing record that are not on the new record will be removed.

Type:
  • string
Default Value:
  • "merge"
Source:

recordOpts :Object

Options to be passed into Mapper#createRecord when wrapping records in Mapper#RecordClass.

Type:
  • Object
Default Value:
  • null
Source:

Methods


<static> extend(props, classProps)

Create a Collection subclass.

Parameters:
Name Type Argument Default Description
props Object <optional>
{}

Properties to add to the prototype of the subclass.

classProps Object <optional>
{}

Static properties to add to the subclass.

Source:
Returns:

Subclass of Collection.

Type
function
Example
var MyCollection = Collection.extend({
  foo: function () { return 'bar' }
})
var collection = new MyCollection()
collection.foo() // "bar"

add(data, opts)

Insert the provided record or records.

If a record is already in the collection then the provided record will either merge with or replace the existing record based on the value of the onConflict option.

The collection's secondary indexes will be updated as each record is visited.

Parameters:
Name Type Argument Description
data Object | Array.<Object> | Record | Array.<Record>

The record or records to insert.

opts Object <optional>

Configuration options.

Properties
Name Type Argument Description
onConflict string <optional>

What to do when a record is already in the collection. Possible values are merge or replace.

Source:
Returns:

The added record or records.

Type
Object | Array.<Object> | Record | Array.<Record>

afterRemove(id, opts, record)

Lifecycle hook called by Collection#remove. If this method returns a value then Collection#remove will return that same value.

Parameters:
Name Type Description
id string | number

The id argument passed to Collection#remove.

opts Object

The opts argument passed to Collection#remove.

record Object

The result that will be returned by Collection#remove.

Source:

afterRemoveAll(query, opts, records)

Lifecycle hook called by Collection#removeAll. If this method returns a value then Collection#removeAll will return that same value.

Parameters:
Name Type Description
query Object

The query argument passed to Collection#removeAll.

opts Object

The opts argument passed to Collection#removeAll.

records Object

The result that will be returned by Collection#removeAll.

Source:

beforeAdd(records, opts)

Lifecycle hook called by Collection#add. If this method returns a value then the records argument in Collection#add will be re-assigned to the returned value.

Parameters:
Name Type Description
records Object | Array.<Object> | Record | Array.<Record>

The records argument passed to Collection#add.

opts Object

The opts argument passed to Collection#add.

Source:

beforeRemove(id, opts)

Lifecycle hook called by Collection#remove.

Parameters:
Name Type Description
id string | number

The id argument passed to Collection#remove.

opts Object

The opts argument passed to Collection#remove.

Source:

beforeRemoveAll(query, opts)

Lifecycle hook called by Collection#removeAll.

Parameters:
Name Type Description
query Object

The query argument passed to Collection#removeAll.

opts Object

The opts argument passed to Collection#removeAll.

Source:

between(leftKeys, rightKeys, opts)

Find all records between two boundaries.

Shortcut for collection.query().between(18, 30, { index: 'age' }).run()

Parameters:
Name Type Argument Description
leftKeys Array

Keys defining the left boundary.

rightKeys Array

Keys defining the right boundary.

opts Object <optional>

Configuration options.

Properties
Name Type Argument Default Description
index string <optional>

Name of the secondary index to use in the query. If no index is specified, the main index is used.

leftInclusive boolean <optional>
true

Whether to include records on the left boundary.

rightInclusive boolean <optional>
false

Whether to include records on the left boundary.

limit boolean <optional>

Limit the result to a certain number.

offset boolean <optional>

The number of resulting records to skip.

Source:
Returns:

The result.

Type
Array
Examples

Get all users ages 18 to 30

const users = collection.between(18, 30, { index: 'age' })

Same as above

const users = collection.between([18], [30], { index: 'age' })

createIndex(name, fieldList)

Create a new secondary index on the contents of the collection.

Parameters:
Name Type Argument Description
name string

The name of the new secondary index.

fieldList Array.<string> <optional>

Array of field names to use as the key or compound key of the new secondary index. If no fieldList is provided, then the name will also be the field that is used to index the collection.

Source:
Returns:

A reference to itself for chaining.

Type
Collection
Examples

Index users by age

collection.createIndex('age')

Index users by status and role

collection.createIndex('statusAndRole', ['status', 'role'])

emit(event, arg)

TODO

Parameters:
Name Type Argument Description
event string

TODO.

arg * <optional>
<repeatable>

TODO

Source:

filter(queryOrFn, thisArg)

Find the record or records that match the provided query or pass the provided filter function.

Shortcut for collection.query().filter(queryOrFn[, thisArg]).run()

Parameters:
Name Type Argument Default Description
queryOrFn Object | function <optional>
{}

Selection query or filter function.

thisArg Object <optional>

Context to which to bind queryOrFn if queryOrFn is a function.

Source:
Returns:

The result.

Type
Array
Examples

Get the draft posts created less than three months

const posts = collection.filter({
  where: {
    status: {
      '==': 'draft'
    },
    created_at_timestamp: {
      '>=': (new Date().getTime() - (1000 * 60 * 60 * 24 * 30 * 3)) // 3 months ago
    }
  }
})

Use a custom filter function

const posts = collection.filter(function (post) {
  return post.isReady()
})

forEach(forEachFn, thisArg)

Iterate over all records.

Parameters:
Name Type Argument Description
forEachFn function

Iteration function.

thisArg * <optional>

Context to which to bind forEachFn.

Source:
Returns:

The result.

Type
Array
Example
collection.forEach(function (record) {
  // do something
})

get(id)

Get the record with the given id.

Parameters:
Name Type Description
id string | number

The primary key of the record to get.

Source:
Returns:

The record with the given id.

Type
Object | Record

getAll(keyList, opts)

Find the record or records that match the provided keyLists.

Shortcut for collection.query().getAll(keyList1, keyList2, ...).run()

Parameters:
Name Type Argument Description
keyList Array <optional>
<repeatable>

Provide one or more keyLists, and all records matching each keyList will be retrieved. If no keyLists are provided, all records will be returned.

opts Object <optional>

Configuration options.

Properties
Name Type Argument Description
index string <optional>

Name of the secondary index to use in the query. If no index is specified, the main index is used.

Source:
Returns:

The result.

Type
Array
Examples

Get the posts where "status" is "draft" or "inReview"

const posts = collection.getAll('draft', 'inReview', { index: 'status' })

Same as above

const posts = collection.getAll(['draft'], ['inReview'], { index: 'status' })

limit(num)

Limit the result.

Shortcut for collection.query().limit(maximumNumber).run()

Parameters:
Name Type Description
num number

The maximum number of records to keep in the result.

Source:
Returns:

The result.

Type
Array
Example
const posts = collection.limit(10)

map(mapFn, thisArg)

Apply a mapping function to all records.

Parameters:
Name Type Argument Description
mapFn function

Mapping function.

thisArg * <optional>

Context to which to bind mapFn.

Source:
Returns:

The result of the mapping.

Type
Array
Example
const names = collection.map(function (user) {
  return user.name
})

mapCall(funcName)

Return the result of calling the specified function on each record in this collection's main index.

Parameters:
Name Type Description
funcName string

Name of function to call

Source:
Returns:

The result.

Type
Array

method(result, opts)

Lifecycle hook called by Collection#add. If this method returns a value then Collection#add will return that same value.

Parameters:
Name Type Description
result Object | Array.<Object> | Record | Array.<Record>

The record or records that were added to this Collection by Collection#add.

opts Object

The opts argument passed to Collection#add.

Source:

off(event, handler)

TODO

Parameters:
Name Type Argument Description
event string <optional>

TODO.

handler function <optional>

TODO

Source:

on(event, handler)

TODO

Parameters:
Name Type Description
event string

TODO.

handler function

TODO

Source:

query()

Create a new query to be executed against the contents of the collection. The result will be all or a subset of the contents of the collection.

Source:
Returns:

New query object.

Type
Query
Example

Grab page 2 of users between ages 18 and 30

collection.query()
  .between(18, 30, { index: 'age' }) // between ages 18 and 30
  .skip(10) // second page
  .limit(10) // page size
  .run()

recordId(record)

Return the primary key of the given, or if no record is provided, return the name of the field that holds the primary key of records in this Collection.

Parameters:
Name Type Argument Description
record Object | Record <optional>

The record whose primary key is to be returned.

Source:
Returns:

Primary key or name of field that holds primary key.

Type
string | number

reduce(cb, initialValue)

Reduce the data in the collection to a single value and return the result.

Parameters:
Name Type Description
cb function

Reduction callback.

initialValue *

Initial value of the reduction.

Source:
Returns:

The result.

Type
*
Example
const totalVotes = collection.reduce(function (prev, record) {
  return prev + record.upVotes + record.downVotes
}, 0)

remove(id, opts)

Remove the record with the given id from this Collection.

Parameters:
Name Type Argument Description
id string | number

The primary key of the record to be removed.

opts Object <optional>

Configuration options.

Source:
Returns:

The removed record, if any.

Type
Object | Record

removeAll(query, opts)

Remove the record selected by "query" from this collection.

Parameters:
Name Type Argument Default Description
query Object <optional>
{}

Selection query.

Properties
Name Type Argument Description
where Object <optional>

Filtering criteria.

skip number <optional>

Number to skip.

limit number <optional>

Number to limit to.

orderBy Array <optional>

Sorting criteria.

opts Object <optional>

Configuration options.

Source:
Returns:

The removed records, if any.

Type
Array.<Object> | Array.<Record>

skip(num)

Skip a number of results.

Shortcut for collection.query().skip(numberToSkip).run()

Parameters:
Name Type Description
num number

The number of records to skip.

Source:
Returns:

The result.

Type
Array
Example
const posts = collection.skip(10)

toJSON(opts)

Return the plain JSON representation of all items in this collection. Assumes records in this collection have a toJSON method.

Parameters:
Name Type Argument Description
opts Object <optional>

Configuration options.

Properties
Name Type Argument Description
with Array.<string> <optional>

Array of relation names or relation fields to include in the representation.

Source:
Returns:

The records.

Type
Array

updateIndex(record, opts)

Update a record's position in a single index of this collection. See Collection#updateIndexes to update a record's position in all indexes at once.

Parameters:
Name Type Argument Description
record Object

The record to update.

opts Object <optional>

Configuration options.

Properties
Name Type Argument Description
index string <optional>

The index in which to update the record's position. If you don't specify an index then the record will be updated in the main index.

Source:

updateIndexes(record, opts)

TODO

Parameters:
Name Type Argument Description
record Object

TODO

opts Object <optional>

Configuration options.

Source: