Class: Collection

Collection


new Collection(records, opts)

An ordered set of Record instances.

Method 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
commitOnMerge String <optional>

See Collection#commitOnMerge.

idAttribute String <optional>

See Collection#idAttribute.

onConflict String <optional>
"merge"

See Collection#onConflict.

mapper String <optional>

See Collection#mapper.

Details
Since Source
3.0.0 Collection.js, line 56
Example

// import {Collection, Record} from 'js-data'
const JSData = require('js-data@3.0.0-beta.7')
const {Collection, Record} = JSData
console.log('Using JSData v' + JSData.version.full)

const user1 = new Record({ id: 1 })
const user2 = new Record({ id: 2 })
const UserCollection = new Collection([user1, user2])
console.log(UserCollection.get(1) === user1)

Extends

This class extends the Component class.

Members


_listeners

Event listeners attached to this Component. Do not modify. Use Component#on and Component#off instead.

Details
Type Since Source
Object 3.0.0 Component.js, line 52
Inherited From:

commitOnMerge

Whether to call Record#commit on records that are added to the collection and already exist in the collection.

Details
Type Default value Source
Boolean
true
Collection.js, line 9

debug

Whether to enable debug-level logs for this component. Anything that extends Component inherits this option and the corresponding logging functionality.

Details
Type Since Default value Source
Boolean 3.0.0
false
Component.js, line 28
Inherited From:
Example

// Normally you would do: import {Component} from 'js-data'
const JSData = require('js-data@3.0.0-beta.7')
const {Component} = JSData
console.log('Using JSData v' + JSData.version.full)

const component = new Component()
component.log('debug', 'some message') // nothing gets logged
// Display debug logs:
component.debug = true
component.log('debug', 'other message') // this DOES get logged

idAttribute

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.

Details
Type Default value Source
String
"id"
Collection.js, line 19

index

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

Details
Type Source
Index Collection.js, line 143

indexes

Object that holds the secondary indexes of this collection.

Details
Type Source
Object.<string, Index> Collection.js, line 157

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.

Details
Type Since Default value Source
Mapper 3.0.0
null
Collection.js, line 98
Example

// Normally you would do: import {Collection, Mapper} from 'js-data'
const JSData = require('js-data@3.0.0-beta.7')
const {Collection, Mapper} = JSData
console.log('Using JSData v' + JSData.version.full)

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

onConflict

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.

Details
Type Default value Source
String
"merge"
Collection.js, line 30

Methods


<static> extend(props, classProps)

Create a subclass of this Collection:

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

Properties to add to the prototype of the subclass.

Properties
Name Type Argument Description
constructor Object <optional>

Provide a custom constructor function to be used as the subclass itself.

classProps Object <optional>
{}

Static properties to add to the subclass.

Return value:
Type Description
Constructor

Subclass of this Collection class.

Details
Since Source
3.0.0 Collection.js, line 858
Example

// Normally you would do: import {Collection} from 'js-data'
const JSData = require('js-data@3.0.0-beta.7')
const {Collection} = JSData
console.log('Using JSData v' + JSData.version.full)

// Extend the class using ES2015 class syntax.
class CustomCollectionClass extends Collection {
  foo () { return 'bar' }
  static beep () { return 'boop' }
}
const customCollection = new CustomCollectionClass()
console.log(customCollection.foo())
console.log(CustomCollectionClass.beep())

// Extend the class using alternate method.
const OtherCollectionClass = Collection.extend({
  foo () { return 'bar' }
}, {
  beep () { return 'boop' }
})
const otherCollection = new OtherCollectionClass()
console.log(otherCollection.foo())
console.log(OtherCollectionClass.beep())

// Extend the class, providing a custom constructor.
function AnotherCollectionClass () {
  Collection.call(this)
  this.created_at = new Date().getTime()
}
Collection.extend({
  constructor: AnotherCollectionClass,
  foo () { return 'bar' }
}, {
  beep () { return 'boop' }
})
const anotherCollection = new AnotherCollectionClass()
console.log(anotherCollection.created_at)
console.log(anotherCollection.foo())
console.log(AnotherCollectionClass.beep())

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.

Method 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 Default Description
commitOnMerge Boolean <optional>
true

See Collection#commitOnMerge.

onConflict String <optional>

See Collection#onConflict.

Return value:
Type Description
Object | Array.<Object> | Record | Array.<Record>

The added record or records.

Details
Since Source
3.0.0 Collection.js, line 189

afterRemove(id, opts, record)

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

Method 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.

Details
Since Source
3.0.0 Collection.js, line 299

afterRemoveAll(query, opts, records)

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

Method 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.

Details
Since Source
3.0.0 Collection.js, line 311

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.

Method 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.

Details
Since Source
3.0.0 Collection.js, line 324

beforeRemove(id, opts)

Lifecycle hook called by Collection#remove.

Method parameters:
Name Type Description
id String | Number

The id argument passed to Collection#remove.

opts Object

The opts argument passed to Collection#remove.

Details
Since Source
3.0.0 Collection.js, line 336

beforeRemoveAll(query, opts)

Lifecycle hook called by Collection#removeAll.

Method parameters:
Name Type Description
query Object

The query argument passed to Collection#removeAll.

opts Object

The opts argument passed to Collection#removeAll.

Details
Since Source
3.0.0 Collection.js, line 346

between(leftKeys, rightKeys, opts)

Find all records between two boundaries.

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

Method 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.

Return value:
Type Description
Array.<Object> | Array.<Record>

The result.

Details
Since Source
3.0.0 Collection.js, line 356
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.

Method 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.

Details
Since Source
3.0.0 Collection.js, line 388
Examples
// Index users by age
collection.createIndex('age')
// Index users by status and role
collection.createIndex('statusAndRole', ['status', 'role'])

dbg(args)

Log the provided values at the "debug" level. Debug-level logs are only logged if Component#debug is true.

.dbg(...) is shorthand for .log('debug', ...).

Method parameters:
Name Type Argument Description
args * <optional>
<repeatable>

Values to log.

Details
Since Source
3.0.0 Component.js, line 123
Inherited From:

emit(event, args)

Trigger an event on this Component.

Method parameters:
Name Type Argument Description
event String

Name of event to emit.

args * <optional>
<repeatable>

Arguments to pass to any listeners.

Details
Since Source
3.0.0 Component.js, line 201
Inherited From:
Example

// import {Collection, DataStore} from 'js-data'
const JSData = require('js-data@3.0.0-beta.7')
const {Collection, DataStore} = JSData

const collection = new Collection()
collection.on('foo', (msg) => {
  console.log(msg)
})
collection.emit('foo', 'bar')

const store = new DataStore()
store.on('beep', (msg) => {
  console.log(msg)
})
store.emit('beep', 'boop')

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()

Method 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.

Return value:
Type Description
Array

The result.

Details
Since Source See
3.0.0 Collection.js, line 416
Example

// Normally you would do: import {Collection} from 'js-data'
const JSData = require('js-data@3.0.0-beta.7')
const {Collection} = JSData
console.log('Using JSData v' + JSData.version.full)

const collection = new Collection([
  { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() }
])

// Get the draft posts created less than three months ago
let posts = collection.filter({
  where: {
    status: {
      '==': 'draft'
    },
    created_at_timestamp: {
      '>=': (new Date().getTime() - (1000 \* 60 \* 60 \* 24 \* 30 \* 3)) // 3 months ago
    }
  }
})
console.log(posts)

// Use a custom filter function
posts = collection.filter(function (post) {
  return post.id % 2 === 0
})

forEach(forEachFn, thisArg)

Iterate over all records.

Method parameters:
Name Type Argument Description
forEachFn Function

Iteration function.

thisArg * <optional>

Context to which to bind forEachFn.

Return value:
Type Description
Array

The result.

Details
Since Source
3.0.0 Collection.js, line 463
Example
collection.forEach(function (record) {
  // do something
})

get(id)

Get the record with the given id.

Method parameters:
Name Type Description
id String | Number

The primary key of the record to get.

Return value:
Type Description
Object | Record

The record with the given id.

Details
Since Source
3.0.0 Collection.js, line 481

getAll(keyList, opts)

Find the record or records that match the provided keyLists.

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

Method 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.

Return value:
Type Description
Array

The result.

Details
Since Source
3.0.0 Collection.js, line 494
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' })

getIndex(name)

Return the index with the given name. If no name is provided, return the main index. Throws an error if the specified index does not exist.

Method parameters:
Name Type Argument Description
name String <optional>

The name of the index to retrieve.

Details
Since Source
3.0.0 Collection.js, line 521

limit(num)

Limit the result.

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

Method parameters:
Name Type Description
num Number

The maximum number of records to keep in the result.

Return value:
Type Description
Array

The result.

Details
Since Source
3.0.0 Collection.js, line 537
Example
const posts = collection.limit(10)

log(level, args)

Log the provided values. By default sends values to console[level]. Debug-level logs are only logged if Component#debug is true.

Will attempt to use appropriate console methods if they are available.

Method parameters:
Name Type Argument Description
level String

Log level.

args * <optional>
<repeatable>

Values to log.

Details
Since Source
3.0.0 Component.js, line 133
Inherited From:

map(mapFn, thisArg)

Apply a mapping function to all records.

Method parameters:
Name Type Argument Description
mapFn Function

Mapping function.

thisArg * <optional>

Context to which to bind mapFn.

Return value:
Type Description
Array

The result of the mapping.

Details
Since Source
3.0.0 Collection.js, line 554
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.

Method parameters:
Name Type Description
funcName String

Name of function to call

Return value:
Type Description
Array

The result.

Details
Since Source
3.0.0 Collection.js, line 576

method(result, opts)

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

Method 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.

Details
Since Source
3.0.0 Collection.js, line 287

off(event, listener)

Remove an event listener from this Component. If no listener is provided, then all listeners for the specified event will be removed. If no event is specified then all listeners for all events will be removed.

Method parameters:
Name Type Argument Description
event String <optional>

Name of event to unsubsribe to.

listener Function <optional>

Listener to remove.

Details
Since Source
3.0.0 Component.js, line 179
Inherited From:
Examples
// Remove a particular listener for a particular event
collection.off('add', handler)
// Remove all listeners for a particular event
record.off('change')
// Remove all listeners to all events
store.off()

on(event, listener, ctx)

Register a new event listener on this Component.

Method parameters:
Name Type Argument Description
event String

Name of event to subsribe to.

listener Function

Listener function to handle the event.

ctx * <optional>

Optional content in which to invoke the listener.

Details
Since Source
3.0.0 Component.js, line 146
Inherited From:
Examples
// Listen for all "afterCreate" events in a DataStore
store.on('afterCreate', (mapperName, props, opts, result) => {
  console.log(mapperName) // "post"
  console.log(props.id) // undefined
  console.log(result.id) // 1234
})
store.create('post', { title: 'Modeling your data' }).then((post) => {
  console.log(post.id) // 1234
})
// Listen for the "add" event on a collection
collection.on('add', (records) => {
  console.log(records) // [...]
})
// Listen for "change" events on a record
post.on('change', (record, changes) => {
  console.log(changes) // { changed: { title: 'Modeling your data' } }
})
post.title = 'Modeling your data'

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.

Return value:
Type Description
Query

New query object.

Details
Since Source
3.0.0 Collection.js, line 612
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.

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

The record whose primary key is to be returned.

Return value:
Type Description
String | Number

Primary key or name of field that holds primary key.

Details
Since Source
3.0.0 Collection.js, line 594

reduce(cb, initialValue)

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

Method parameters:
Name Type Description
cb Function

Reduction callback.

initialValue *

Initial value of the reduction.

Return value:
Type Description
*

The result.

Details
Since Source
3.0.0 Collection.js, line 633
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.

Method parameters:
Name Type Argument Description
id String | Number

The primary key of the record to be removed.

opts Object <optional>

Configuration options.

Return value:
Type Description
Object | Record

The removed record, if any.

Details
Since Source
3.0.0 Collection.js, line 652

removeAll(query, opts)

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

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

Selection query. See query.

Properties
Name Type Argument Description
where Object <optional>

See query.where.

offset Number <optional>

See query.offset.

limit Number <optional>

See query.limit.

orderBy String | Array.<Array> <optional>

See query.orderBy.

opts Object <optional>

Configuration options.

Return value:
Type Description
Array.<Object> | Array.<Record>

The removed records, if any.

Details
Since Source
3.0.0 Collection.js, line 683

skip(num)

Skip a number of results.

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

Method parameters:
Name Type Description
num Number

The number of records to skip.

Return value:
Type Description
Array

The result.

Details
Since Source
3.0.0 Collection.js, line 714
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.

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.

Return value:
Type Description
Array

The records.

Details
Since Source
3.0.0 Collection.js, line 731

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.

Method 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.

Details
Since Source
3.0.0 Collection.js, line 746

updateIndexes(record)

Updates all indexes in this collection for the provided record. Has no effect if the record is not in the collection.

Method parameters:
Name Type Description
record Object

TODO

Details
Since Source
3.0.0 Collection.js, line 764

Type Definitions


addListener(The)

Callback signature for the Collection#event:add event.

Method parameters:
Name Type Description
The Record | Array.<Record>

Record or Records that were added.

Details
Type Since Source See
Function 3.0.0 Collection.js, line 814
Example
function onAdd (recordOrRecords) {
  // do something
}
collection.on('add', onAdd)

changeListener(The, The)

Callback signature for the Collection#event:change event.

Method parameters:
Name Type Description
The Record

Record that changed.

The Object

changes.

Details
Type Since Source See
Function 3.0.0 Collection.js, line 788
Example
function onChange (record, changes) {
  // do something
}
collection.on('change', onChange)

removeListener(Record)

Callback signature for the Collection#event:remove event.

Method parameters:
Name Type Description
Record Record | Array.<Record>

or Records that were removed.

Example
function onRemove (recordsOrRecords) {
  // do something
}
collection.on('remove', onRemove)

Events


add

Fired when one or more records are added to the Collection. See Collection~addListener on how to listen for this event.


change

Fired when a record changes. Only works for records that have tracked changes. See Collection~changeListener on how to listen for this event.


remove

Fired when one or more records are removed from the Collection. See Collection~removeListener for how to listen for this event.