Class: DataStore

DataStore


new DataStore(opts)

The DataStore class is an extension of SimpleStore. Not only does DataStore manage mappers and store data in collections, it uses the LinkedCollection class to link related records together in memory.

import {DataStore} from 'js-data'
Method parameters:
Name Type Argument Description
opts Object <optional>

Configuration options. See SimpleStore.

Properties
Name Type Argument Default Description
collectionClass Boolean <optional>
LinkedCollection

See DataStore#collectionClass.

debug Boolean <optional>
false

See Component#debug.

unlinkOnDestroy Boolean <optional>
true

See DataStore#unlinkOnDestroy.

usePendingFind Boolean | Function <optional>
true

See DataStore#usePendingFind.

usePendingFindAll Boolean | Function <optional>
true

See DataStore#usePendingFindAll.

Return value:
Type Description
DataStore Unspecified
Example
import {DataStore} from 'js-data'
import HttpAdapter from 'js-data-http'
const store = new DataStore()

// DataStore#defineMapper returns a direct reference to the newly created
// Mapper.
const UserMapper = store.defineMapper('user')

// DataStore#as returns the store scoped to a particular Mapper.
const UserStore = store.as('user')

// Call "find" on "UserMapper" (Stateless ORM)
UserMapper.find(1).then((user) => {
  // retrieved a "user" record via the http adapter, but that's it

  // Call "find" on "store" targeting "user" (Stateful DataStore)
  return store.find('user', 1) // same as "UserStore.find(1)"
}).then((user) => {
  // not only was a "user" record retrieved, but it was added to the
  // store's "user" collection
  const cachedUser = store.getCollection('user').get(1)
  console.log(user === cachedUser) // true
})

Extends

This class extends the SimpleStore class.

Members


_adapters

The adapters registered with this Container, which are also shared by all Mappers in this Container.

Details
Type Since Source See
Object 3.0.0 Container.js, line 941
Inherited From:

_mappers

The the mappers in this container

Details
Type Since Source See
Object 3.0.0 Container.js, line 954
Inherited From:

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-rc.4')
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

mapperClass

Constructor function to use in Container#defineMapper to create new Mapper instances. Container#mapperClass should extend Mapper. By default Mapper is used to instantiate Mappers.

Details
Type Since Source See
Constructor 3.0.0 Container.js, line 966
Inherited From:
Example

// import {Container, Mapper} from 'js-data'
const JSData = require('js-data@3.0.0-rc.4')
const {Container} = JSData
console.log('Using JSData v' + JSData.version.full)

class MyMapperClass extends Mapper {
  foo () { return 'bar' }
}
const store = new Container({
  mapperClass: MyMapperClass
})
store.defineMapper('user')
console.log(store.getMapper('user').foo())

mapperDefaults

Defaults options to pass to Container#mapperClass when creating a new Mapper.

Details
Type Since Default value Source
Object 3.0.0
{}
Container.js, line 1000
Inherited From:
Example

// import {Container} from 'js-data'
const JSData = require('js-data@3.0.0-rc.4')
const {Container} = JSData
console.log('Using JSData v' + JSData.version.full)

const store = new Container({
  mapperDefaults: {
    idAttribute: '_id'
  }
})
store.defineMapper('user')
console.log(store.getMapper('user').idAttribute)

unlinkOnDestroy

Whether in-memory relations should be unlinked from records after they are destroyed.

Details
Type Since Default value Source
Boolean 3.0.0
true
DataStore.js, line 12

usePendingFind

Whether to use the pending query if a find request for the specified record is currently underway. Can be set to true, false, or to a function that returns true or false.

Details
Type Since Default value Source
Boolean | Function 3.0.0
true
SimpleStore.js, line 274
Inherited From:

usePendingFindAll

Whether to use the pending query if a findAll request for the given query is currently underway. Can be set to true, false, or to a function that returns true or false.

Details
Type Since Default value Source
Boolean | Function 3.0.0
true
SimpleStore.js, line 286
Inherited From:

Methods


<static> extend(props, classProps)

Create a subclass of this DataStore:

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 DataStore class.

Details
Since Source
3.0.0 DataStore.js, line 471
Example

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

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

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

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

add(name, data, opts)

Wrapper for Collection#add.

Method parameters:
Name Type Argument Description
name String | Number

Name of the Mapper to target.

data Object | Array.<Object> | Record | Array.<Record>

See Collection#add.

opts Object <optional>

Configuration options. See Collection#add.

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

See Collection#add.

Details
Since Source See
3.0.0 SimpleStore.js, line 13
Inherited From:
Example

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

const store = new SimpleStore()
store.defineMapper('book')

// Add one book to the in-memory store:
store.add('book', { id: 1, title: 'Respect your Data' })
// Add multiple books to the in-memory store:
store.add('book', [
  { id: 2, title: 'Easy data recipes' },
  { id: 3, title: 'Active Record 101' }
])

addToCache(name, data, opts)

This method takes the data received from SimpleStore#find, SimpleStore#findAll, SimpleStore#update, etc., and adds the data to the store. You don't need to call this method directly.

If you're using the http adapter and your response data is in an unexpected format, you may need to override this method so the right data gets added to the store.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

data *

Data from which data should be selected for add.

opts Object <optional>

Configuration options.

Details
Source
SimpleStore.js, line 444
Inherited From:
Examples
const store = new SimpleStore({
  addToCache (mapperName, data, opts) {
    // Let's say for a particular Resource, response data is in a weird format
    if (name === 'comment') {
      // Re-assign the variable to add the correct records into the stores
      data = data.items
    }
    // Now perform default behavior
    return SimpleStore.prototype.addToCache.call(this, mapperName, data, opts)
  }
})
// Extend using ES2015 class syntax.
class MyStore extends SimpleStore {
  addToCache (mapperName, data, opts) {
    // Let's say for a particular Resource, response data is in a weird format
    if (name === 'comment') {
      // Re-assign the variable to add the correct records into the stores
      data = data.items
    }
    // Now perform default behavior
    return super.addToCache(mapperName, data, opts)
  }
}
const store = new MyStore()

as(name)

Return the store scoped to a particular mapper/collection pair.

Method parameters:
Name Type Description
name String

Name of the Mapper.

Return value:
Type Description
Object

The store, scoped to a particular Mapper/Collection pair.

Details
Since Source
3.0.0 SimpleStore.js, line 490
Inherited From:
Example

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

const store = new SimpleStore()
const UserMapper = store.defineMapper('user')
const UserStore = store.as('user')

const user1 = store.createRecord('user', { name: 'John' })
const user2 = UserStore.createRecord({ name: 'John' })
const user3 = UserMapper.createRecord({ name: 'John' })
console.log(user1 === user2)
console.log(user2 === user3)
console.log(user1 === user3)

between(name, leftKeys, rightKeys, opts)

Wrapper for Collection#between.

Method parameters:
Name Type Argument Description
name String | Number

Name of the Mapper to target.

leftKeys Array

See Collection#between.

rightKeys Array

See Collection#between.

opts Object <optional>

Configuration options. See Collection#between.

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

See Collection#between.

Inherited From:
Examples
// Get all users ages 18 to 30
const users = store.between('user', 18, 30, { index: 'age' })
// Same as above
const users = store.between('user', [18], [30], { index: 'age' })

cachedFind(name, id, opts)

Retrieve a cached find result, if any. This method is called during SimpleStore#find to determine if Mapper#find needs to be called. If this method returns undefined then Mapper#find will be called. Otherwise SimpleStore#find will immediately resolve with the return value of this method.

When using SimpleStore in the browser, you can override this method to implement your own cache-busting strategy.

Method parameters:
Name Type Description
name String

The name argument passed to SimpleStore#find.

id String | Number

The id argument passed to SimpleStore#find.

opts Object

The opts argument passed to SimpleStore#find.

Details
Since Source
3.0.0 SimpleStore.js, line 545
Inherited From:
Examples
const store = new SimpleStore({
  cachedFind (mapperName, id, opts) {
    // Let's say for a particular Resource, we always want to pull fresh from the server
    if (mapperName === 'schedule') {
      // Return undefined to trigger a Mapper#find call
      return
    }
    // Otherwise perform default behavior
    return SimpleStore.prototype.cachedFind.call(this, mapperName, id, opts)
  }
})
// Extend using ES2015 class syntax.
class MyStore extends SimpleStore {
  cachedFind (mapperName, id, opts) {
    // Let's say for a particular Resource, we always want to pull fresh from the server
    if (mapperName === 'schedule') {
      // Return undefined to trigger a Mapper#find call
      return
    }
    // Otherwise perform default behavior
    return super.cachedFind(mapperName, id, opts)
  }
}
const store = new MyStore()

cachedFindAll(name, hash, opts)

Retrieve a cached findAll result, if any. This method is called during SimpleStore#findAll to determine if Mapper#findAll needs to be called. If this method returns undefined then Mapper#findAll will be called. Otherwise SimpleStore#findAll will immediately resolve with the return value of this method.

When using SimpleStore in the browser, you can override this method to implement your own cache-busting strategy.

Method parameters:
Name Type Description
name String

The name argument passed to SimpleStore#findAll.

hash String

The result of calling SimpleStore#hashQuery on the query argument passed to SimpleStore#findAll.

opts Object

The opts argument passed to SimpleStore#findAll.

Details
Since Source
3.0.0 SimpleStore.js, line 591
Inherited From:
Examples
const store = new SimpleStore({
  cachedFindAll (mapperName, hash, opts) {
    // Let's say for a particular Resource, we always want to pull fresh from the server
    if (mapperName === 'schedule') {
      // Return undefined to trigger a Mapper#findAll call
      return undefined
    }
    // Otherwise perform default behavior
    return SimpleStore.prototype.cachedFindAll.call(this, mapperName, hash, opts)
  }
})
// Extend using ES2015 class syntax.
class MyStore extends SimpleStore {
  cachedFindAll (mapperName, hash, opts) {
    // Let's say for a particular Resource, we always want to pull fresh from the server
    if (mapperName === 'schedule') {
      // Return undefined to trigger a Mapper#findAll call
      return undefined
    }
    // Otherwise perform default behavior
    return super.cachedFindAll(mapperName, hash, opts)
  }
}
const store = new MyStore()

cacheFind(name, data, id, opts)

Mark a Mapper#find result as cached by adding an entry to SimpleStore#_completedQueries. By default, once a find entry is added it means subsequent calls to the same Resource with the same id argument will immediately resolve with the result of calling SimpleStore#get instead of delegating to Mapper#find.

As part of implementing your own caching strategy, you may choose to override this method.

Method parameters:
Name Type Description
name String

The name argument passed to SimpleStore#find.

data *

The result to cache.

id String | Number

The id argument passed to SimpleStore#find.

opts Object

The opts argument passed to SimpleStore#find.

Details
Since Source
3.0.0 SimpleStore.js, line 638
Inherited From:
Examples
const store = new SimpleStore({
  cacheFind (mapperName, data, id, opts) {
    // Let's say for a particular Resource, we always want to pull fresh from the server
    if (mapperName === 'schedule') {
      // Return without saving an entry to SimpleStore#_completedQueries
      return
    }
    // Otherwise perform default behavior
    return SimpleStore.prototype.cacheFind.call(this, mapperName, data, id, opts)
  }
})
// Extend using ES2015 class syntax.
class MyStore extends SimpleStore {
  cacheFind (mapperName, data, id, opts) {
    // Let's say for a particular Resource, we always want to pull fresh from the server
    if (mapperName === 'schedule') {
      // Return without saving an entry to SimpleStore#_completedQueries
      return
    }
    // Otherwise perform default behavior
    return super.cacheFind(mapperName, data, id, opts)
  }
}
const store = new MyStore()

cacheFindAll(name, data, hash, opts)

Mark a Mapper#findAll result as cached by adding an entry to SimpleStore#_completedQueries. By default, once a findAll entry is added it means subsequent calls to the same Resource with the same query argument will immediately resolve with the result of calling SimpleStore#filter instead of delegating to Mapper#findAll.

As part of implementing your own caching strategy, you may choose to override this method.

Method parameters:
Name Type Description
name String

The name argument passed to SimpleStore#findAll.

data *

The result to cache.

hash String

The result of calling SimpleStore#hashQuery on the query argument passed to SimpleStore#findAll.

opts Object

The opts argument passed to SimpleStore#findAll.

Details
Since Source
3.0.0 SimpleStore.js, line 687
Inherited From:
Examples
const store = new SimpleStore({
  cachedFindAll (mapperName, data, hash, opts) {
    // Let's say for a particular Resource, we always want to pull fresh from the server
    if (mapperName === 'schedule') {
      // Return without saving an entry to SimpleStore#_completedQueries
      return
    }
    // Otherwise perform default behavior.
    return SimpleStore.prototype.cachedFindAll.call(this, mapperName, data, hash, opts)
  }
})
// Extend using ES2015 class syntax.
class MyStore extends SimpleStore {
  cachedFindAll (mapperName, data, hash, opts) {
    // Let's say for a particular Resource, we always want to pull fresh from the server
    if (mapperName === 'schedule') {
      // Return without saving an entry to SimpleStore#_completedQueries
      return
    }
    // Otherwise perform default behavior.
    return super.cachedFindAll(mapperName, data, hash, opts)
  }
}
const store = new MyStore()

clear()

Remove all records from the in-memory store and reset SimpleStore#_completedQueries.

Return value:
Type Description
Object

Object containing all records that were in the store.

Inherited From:

count(name, query, opts)

Wrapper for Mapper#count.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

query Object <optional>

See Mapper#count.

opts Object <optional>

See Mapper#count.

Return value:
Type Description
Promise

See Mapper#count.

Details
Since Source See
3.0.0 Container.js, line 8
Inherited From:
Example
// Get the number of published blog posts
import {Container} from 'js-data'
import RethinkDBAdapter from 'js-data-rethinkdb'
const store = new Container()
store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true })
store.defineMapper('post')

store.count('post', { status: 'published' }).then((numPublished) => {
  console.log(numPublished) // e.g. 45
})

create(name, record, opts)

Wrapper for Mapper#create. Adds the created record to the store.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

record Object

Passed to Mapper#create.

opts Object <optional>

Passed to Mapper#create. See Mapper#create for more configuration options.

Fires:
Return value:
Type Description
Promise

Resolves with the result of the create.

Details
Since Source
3.0.0 SimpleStore.js, line 807
Inherited From:
Example
import {SimpleStore} from 'js-data'
import {HttpAdapter} from 'js-data-http'

const store = new SimpleStore()
store.registerAdapter('http', new HttpAdapter(), { default: true })

store.defineMapper('book')

// Since this example uses the http adapter, we'll get something like:
//
//   POST /book {"author_id":1234,...}
store.create('book', {
  author_id: 1234,
  edition: 'First Edition',
  title: 'Respect your Data'
}).then((book) => {
  console.log(book.id) // 120392
  console.log(book.title) // "Respect your Data"
})

createIndex(name, name, fieldList)

Wrapper for Collection#createIndex.

Method parameters:
Name Type Argument Description
name String | Number

Name of the Mapper to target.

name String

See Collection#createIndex.

fieldList Array.<String> <optional>

See Collection#createIndex.

Inherited From:
Examples
// Index users by age
store.createIndex('user', 'age')
// Index users by status and role
store.createIndex('user', 'statusAndRole', ['status', 'role'])

createMany(name, records, opts)

Wrapper for Mapper#createMany. Adds the created records to the store.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

records Array

Passed to Mapper#createMany.

opts Object <optional>

Passed to Mapper#createMany. See Mapper#createMany for more configuration options.

Fires:
Return value:
Type Description
Promise

Resolves with the result of the create.

Details
Since Source
3.0.0 SimpleStore.js, line 899
Inherited From:
Example
import {SimpleStore} from 'js-data'
import {HttpAdapter} from 'js-data-http'

const store = new SimpleStore()
store.registerAdapter('http', new HttpAdapter(), { default: true })

store.defineMapper('book')

// Since this example uses the http adapter, we'll get something like:
//
//   POST /book [{"author_id":1234,...},{...}]
store.createMany('book', [{
  author_id: 1234,
  edition: 'First Edition',
  title: 'Respect your Data'
}, {
  author_id: 1234,
  edition: 'Second Edition',
  title: 'Respect your Data'
}]).then((books) => {
  console.log(books[0].id) // 142394
  console.log(books[0].title) // "Respect your Data"
})

createRecord(name, props, opts)

Wrapper for Mapper#createRecord.

Note: This method does not interact with any adapter, and does not save any data. It only creates new objects in memory.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

props Object | Array.<Object>

See Mapper#createRecord.

opts Object <optional>

See Mapper#createRecord.

Return value:
Type Description
Promise

See Mapper#createRecord.

Details
Since Source See
3.0.0 Container.js, line 199
Inherited From:
Example
// Create empty unsaved record instance
import {Container} from 'js-data'
const store = new Container()
store.defineMapper('post')
const post = PostMapper.createRecord()

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 124
Inherited From:

defineMapper(name, opts)

Create a new mapper and register it in this container.

Method parameters:
Name Type Argument Description
name String

Name under which to register the new Mapper. Mapper#name will be set to this value.

opts Object <optional>

Configuration options. Passed to Container#mapperClass when creating the new Mapper.

Return value:
Type Description
Mapper

The newly created instance of Mapper.

Details
Since Source See
3.0.0 Container.js, line 1117
Inherited From:
Example

// import {Container} from 'js-data'
const JSData = require('js-data@3.0.0-rc.4')
const {Container} = JSData
console.log('Using JSData v' + JSData.version.full)

const store = new Container({
  mapperDefaults: { foo: 'bar' }
})
// Container#defineMapper returns a direct reference to the newly created
// Mapper.
const UserMapper = store.defineMapper('user')
console.log(UserMapper === store.getMapper('user'))
console.log(UserMapper === store.as('user').getMapper())
console.log(UserMapper.foo)

destroy(name, id, opts)

Wrapper for Mapper#destroy. Removes any destroyed record from the in-memory store. Clears out any SimpleStore#_completedQueries entries associated with the provided id.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

id String | Number

Passed to Mapper#destroy.

opts Object <optional>

Passed to Mapper#destroy. See Mapper#destroy for more configuration options.

Fires:
Return value:
Type Description
Promise

Resolves when the destroy operation completes.

Details
Since Source
3.0.0 SimpleStore.js, line 1043
Inherited From:
Example
import {SimpleStore} from 'js-data'
import {HttpAdapter} from 'js-data-http'

const store = new SimpleStore()
store.registerAdapter('http', new HttpAdapter(), { default: true })

store.defineMapper('book')

store.add('book', { id: 1234, title: 'Data Management is Hard' })

// Since this example uses the http adapter, we'll get something like:
//
//   DELETE /book/1234
store.destroy('book', 1234).then(() => {
  // The book record is no longer in the in-memory store
  console.log(store.get('book', 1234)) // undefined

  return store.find('book', 1234)
}).then((book) {
  // The book was deleted from the database too
  console.log(book) // undefined
})

destroyAll(name, query, opts)

Wrapper for Mapper#destroyAll. Removes any destroyed records from the in-memory store.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

query Object <optional>

Passed to Mapper#destroyAll.

opts Object <optional>

Passed to Mapper#destroyAll. See Mapper#destroyAll for more configuration options.

Fires:
Return value:
Type Description
Promise

Resolves when the delete completes.

Details
Since Source
3.0.0 SimpleStore.js, line 1150
Inherited From:
Example
import {SimpleStore} from 'js-data'
import {HttpAdapter} from 'js-data-http'

const store = new SimpleStore()
store.registerAdapter('http', new HttpAdapter(), { default: true })

store.defineMapper('book')

store.add('book', { id: 1234, title: 'Data Management is Hard' })

// Since this example uses the http adapter, we'll get something like:
//
//   DELETE /book/1234
store.destroy('book', 1234).then(() => {
  // The book record is gone from the in-memory store
  console.log(store.get('book', 1234)) // undefined
  return store.find('book', 1234)
}).then((book) {
  // The book was deleted from the database too
  console.log(book) // undefined
})

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 202
Inherited From:
Example

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

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

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

filter(name, queryOrFn, thisArg)

Wrapper for Collection#filter.

Method parameters:
Name Type Argument Default Description
name String | Number

Name of the Mapper to target.

queryOrFn Object | Function <optional>
{}

See Collection#filter.

thisArg Object <optional>

See Collection#filter.

Return value:
Type Description
Array

See Collection#filter.

Details
Since Source See
3.0.0 SimpleStore.js, line 89
Inherited From:
Example

// import {SimpleStore} from 'js-data'
const JSData = require('js-data@3.0.0-rc.4')
const {SimpleStore} = JSData
console.log('Using JSData v' + JSData.version.full)

const store = new SimpleStore()
store.defineMapper('post')
store.add('post', [
  { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() }
])

// Get the draft posts created less than three months ago
let posts = store.filter('post', {
  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 = store.filter('post', function (post) { return post.id % 2 === 0 })

find(name, id, opts)

Wrapper for Mapper#find. Adds any found record to the store.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

id String | Number

Passed to Mapper#find.

opts Object <optional>

Passed to Mapper#find.

Properties
Name Type Argument Description
force Boolean <optional>

Bypass cacheFind

usePendingFind Boolean | Function <optional>

See SimpleStore#usePendingFind

Fires:
Return value:
Type Description
Promise

Resolves with the result, if any.

Details
Since Source
3.0.0 SimpleStore.js, line 1266
Inherited From:
Example
import {SimpleStore} from 'js-data'
import {HttpAdapter} from 'js-data-http'

const store = new SimpleStore()
store.registerAdapter('http', new HttpAdapter(), { default: true })

store.defineMapper('book')

// Since this example uses the http adapter, we'll get something like:
//
//   GET /book/1234
store.find('book', 1234).then((book) => {
  // The book record is now in the in-memory store
  console.log(store.get('book', 1234) === book) // true
})

findAll(name, query, opts)

Wrapper for Mapper#findAll. Adds any found records to the store.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

query Object <optional>

Passed to Mapper.findAll.

opts Object <optional>

Passed to Mapper.findAll.

Properties
Name Type Argument Description
force Boolean <optional>

Bypass cacheFindAll

usePendingFindAll Boolean | Function <optional>

See SimpleStore#usePendingFindAll

Fires:
Return value:
Type Description
Promise

Resolves with the result, if any.

Details
Since Source
3.0.0 SimpleStore.js, line 1378
Inherited From:
Example
import {SimpleStore} from 'js-data'
import {HttpAdapter} from 'js-data-http'

const store = new SimpleStore()
store.registerAdapter('http', new HttpAdapter(), { default: true })

store.defineMapper('movie')

// Since this example uses the http adapter, we'll get something like:
//
//   GET /movie?rating=PG
store.find('movie', { rating: 'PG' }).then((movies) => {
  // The movie records are now in the in-memory store
  console.log(store.filter('movie'))
})

get(name, id)

Wrapper for Collection#get.

Method parameters:
Name Type Description
name String | Number

Name of the Mapper to target.

id String | Number

See Collection#get.

Return value:
Type Description
Object | Record

See Collection#get.

Details
Since Source See
3.0.0 SimpleStore.js, line 131
Inherited From:
Example

// import {SimpleStore} from 'js-data'
const JSData = require('js-data@3.0.0-rc.4')
const {SimpleStore} = JSData
console.log('Using JSData v' + JSData.version.full)

const store = new SimpleStore()
store.defineMapper('post')
store.add('post', [
  { id: 1, status: 'draft', created_at_timestamp: new Date().getTime() }
])

console.log(store.get('post', 1)) // {...}
console.log(store.get('post', 2)) // undefined

getAdapter(name)

Return the registered adapter with the given name or the default adapter if no name is provided.

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

The name of the adapter to retrieve.

Return value:
Type Description
Adapter

The adapter.

Details
Since Source
3.0.0 Container.js, line 1189
Inherited From:

getAdapterName(opts)

Return the name of a registered adapter based on the given name or options, or the name of the default adapter if no name provided.

Method parameters:
Name Type Argument Description
opts Object | String <optional>

The name of an adapter or options, if any.

Return value:
Type Description
String

The name of the adapter.

Details
Since Source
3.0.0 Container.js, line 1206
Inherited From:

getAdapters()

Return the registered adapters of this container.

Return value:
Type Description
Adapter Unspecified
Details
Since Source
3.0.0 Container.js, line 1223
Inherited From:

getAll(name, keyList, opts)

Wrapper for Collection#getAll.

Method parameters:
Name Type Argument Description
name String | Number

Name of the Mapper to target.

keyList Array <optional>
<repeatable>

See Collection#getAll.

opts Object <optional>

See Collection#getAll.

Return value:
Type Description
Array

See Collection#getAll.

Inherited From:
Examples
// Get the posts where "status" is "draft" or "inReview"
const posts = store.getAll('post', 'draft', 'inReview', { index: 'status' })
// Same as above
const posts = store.getAll('post', ['draft'], ['inReview'], { index: 'status' })

getCollection(name)

Return the Collection with the given name, if for some reason you need a direct reference to the collection.

Method parameters:
Name Type Description
name String

Name of the Collection to retrieve.

Throws:

Thrown if the specified Collection does not exist.

Type
Error
Return value:
Type Description
Collection Unspecified
Details
Since Source
3.0.0 SimpleStore.js, line 1441
Inherited From:

getMapper(name)

Return the mapper registered under the specified name.

Method parameters:
Name Type Description
name String

Mapper#name.

Return value:
Type Description
Mapper Unspecified
Details
Since Source
3.0.0 Container.js, line 1234
Inherited From:
Example

// import {Container} from 'js-data'
const JSData = require('js-data@3.0.0-rc.4')
const {Container} = JSData
console.log('Using JSData v' + JSData.version.full)

const store = new Container()
// Container#defineMapper returns a direct reference to the newly created
// Mapper.
const UserMapper = store.defineMapper('user')
console.log(UserMapper === store.getMapper('user'))
console.log(UserMapper === store.as('user').getMapper())
store.getMapper('profile') // throws Error, there is no mapper with name "profile"

getMapperByName(name)

Return the mapper registered under the specified name. Doesn't throw error if mapper doesn't exist.

Method parameters:
Name Type Description
name String

Mapper#name.

Return value:
Type Description
Mapper Unspecified
Details
Since Source
3.0.0 Container.js, line 1264
Inherited From:
Example

// import {Container} from 'js-data'
const JSData = require('js-data@3.0.0-rc.4')
const {Container} = JSData
console.log('Using JSData v' + JSData.version.full)

const store = new Container()
// Container#defineMapper returns a direct reference to the newly created
// Mapper.
const UserMapper = store.defineMapper('user')
console.log(UserMapper === store.getMapper('user'))
console.log(UserMapper === store.as('user').getMapper())
console.log(store.getMapper('profile')) // Does NOT throw an error

getSchema(name)

Wrapper for Mapper#getSchema.

Method parameters:
Name Type Description
name String

Name of the Mapper to target.

Return value:
Type Description
Schema

See Mapper#getSchema.

Details
Since Source See
3.0.0 Container.js, line 533
Inherited From:

hashQuery(name, query)

Hashing function used to cache SimpleStore#find and SimpleStore#findAll requests. This method simply JSONifies the query argument passed to SimpleStore#find or SimpleStore#findAll.

Override this method for custom hashing behavior.

Method parameters:
Name Type Description
name String

The name argument passed to SimpleStore#find or SimpleStore#findAll.

query Object

The query argument passed to SimpleStore#find or SimpleStore#findAll.

Return value:
Type Description
String

The JSONified query.

Details
Since Source
3.0.0 SimpleStore.js, line 1460
Inherited From:

is(name, record)

Wrapper for Mapper#is.

Method parameters:
Name Type Description
name String

Name of the Mapper to target.

record Object | Record

See Mapper#is.

Return value:
Type Description
Boolean

See Mapper#is.

Details
Since Source See
3.0.0 Container.js, line 544
Inherited From:
Example
import {Container} from 'js-data'
const store = new Container()
store.defineMapper('post')
const post = store.createRecord()

console.log(store.is('post', post)) // true
// Equivalent to what's above
console.log(post instanceof store.getMapper('post').recordClass) // true

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 134
Inherited From:

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 180
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 SimpleStore.

Proxy for Container#on. If an event was emitted by a Mapper or Collection in the SimpleStore, then the name of the Mapper or Collection will be prepended to the arugments passed to the provided event handler.

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
Source
SimpleStore.js, line 394
Inherited From:
Examples
// Listen for all "afterCreate" events in a SimpleStore
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
store.on('add', (mapperName, records) => {
  console.log(records) // [...]
})
// Listen for "change" events on a record
store.on('change', (mapperName, record, changes) => {
  console.log(changes) // { changed: { title: 'Modeling your data' } }
})
post.title = 'Modeling your data'

prune(opts)

Wrapper for Collection#prune.

Method parameters:
Name Type Argument Description
opts Object <optional>

See Collection#prune.

Return value:
Type Description
Array

See Collection#prune.

Details
Since Source See
3.0.0 SimpleStore.js, line 181
Inherited From:

query(name)

Wrapper for Collection#query.

Method parameters:
Name Type Description
name String | Number

Name of the Mapper to target.

Return value:
Type Description
Query

See Collection#query.

Details
Since Source See
3.0.0 SimpleStore.js, line 193
Inherited From:
Example
// Grab page 2 of users between ages 18 and 30
store.query('user')
  .between(18, 30, { index: 'age' }) // between ages 18 and 30
  .skip(10) // second page
  .limit(10) // page size
  .run()

registerAdapter(name, adapter, opts)

Register an adapter on this container under the given name. Adapters registered on a container are shared by all mappers in the container.

Method parameters:
Name Type Argument Description
name String

The name of the adapter to register.

adapter Adapter

The adapter to register.

opts Object <optional>

Configuration options.

Properties
Name Type Argument Default Description
default Boolean <optional>
false

Whether to make the adapter the default adapter for all Mappers in this container.

Details
Since Source Tutorials
3.0.0 Container.js, line 1291
Inherited From:
Example
import {Container} from 'js-data'
import {RethinkDBAdapter} from 'js-data-rethinkdb'
const store = new Container()
store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true })

remove(name, id, opts)

Wrapper for Collection#remove. Removes the specified Record from the store.

Method parameters:
Name Type Argument Description
name String

The name of the Collection to target.

id String | Number

The primary key of the Record to remove.

opts Object <optional>

Configuration options.

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

Relations of the Record to also remove from the store.

Fires:
Return value:
Type Description
Record

The removed Record, if any.

Details
Since Source See
3.0.0 SimpleStore.js, line 1484
Inherited From:
Example

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

const store = new SimpleStore()
store.defineMapper('book')
console.log(store.getAll('book').length)
store.add('book', { id: 1234 })
console.log(store.getAll('book').length)
store.remove('book', 1234)
console.log(store.getAll('book').length)

removeAll(name, query, opts)

Wrapper for Collection#removeAll. Removes the selected Records from the store.

Method parameters:
Name Type Argument Default Description
name String

The name of the Collection to target.

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.

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

Relations of the Record to also remove from the store.

Fires:
Return value:
Type Description
Record

The removed Records, if any.

Details
Since Source See
3.0.0 SimpleStore.js, line 1522
Inherited From:
Example

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

const store = new SimpleStore()
store.defineMapper('movie')
console.log(store.getAll('movie').length)
store.add('movie', [{ id: 3, rating: 'R' }, { id: 4, rating: 'PG-13' })
console.log(store.getAll('movie').length)
store.removeAll('movie', { rating: 'R' })
console.log(store.getAll('movie').length)

removeRelated(name, records, opts)

Remove from the store Records that are related to the provided Record(s).

Method parameters:
Name Type Argument Description
name String

The name of the Collection to target.

records Record | Array.<Record>

Records whose relations are to be removed.

opts Object <optional>

Configuration options.

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

Relations of the Record(s) to remove from the store.

Fires:
Details
Since Source
3.0.0 SimpleStore.js, line 1569
Inherited From:

sum(name, field, query, opts)

Wrapper for Mapper#sum.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

field String

See Mapper#sum.

query Object <optional>

See Mapper#sum.

opts Object <optional>

See Mapper#sum.

Return value:
Type Description
Promise

See Mapper#sum.

Details
Since Source See
3.0.0 Container.js, line 566
Inherited From:
Example
import {Container} from 'js-data'
import RethinkDBAdapter from 'js-data-rethinkdb'
const store = new Container()
store.registerAdapter('rethinkdb', new RethinkDBAdapter(), { default: true })
store.defineMapper('purchase_order')

store.sum('purchase_order', 'amount', { status: 'paid' }).then((amountPaid) => {
  console.log(amountPaid) // e.g. 451125.34
})

toJSON(name, opts)

Wrapper for Collection#toJSON.

Method parameters:
Name Type Argument Description
name String | Number

Name of the Mapper to target.

opts Object <optional>

See Collection#toJSON.

Return value:
Type Description
Array

See Collection#toJSON.

Inherited From:
Example
store.defineMapper('post', {
  schema: {
    properties: {
      id: { type: 'number' },
      title: { type: 'string' }
    }
  }
})
store.add('post', [
  { id: 1, status: 'published', title: 'Respect your Data' },
  { id: 2, status: 'draft', title: 'Connecting to a data source' }
])
console.log(store.toJSON('post'))
const draftsJSON = store.query('post')
  .filter({ status: 'draft' })
  .mapCall('toJSON')
  .run()

unsaved()

Wrapper for Collection#unsaved.

Return value:
Type Description
Array

See Collection#unsaved.

Inherited From:

update(name, id, record, opts)

Wrapper for Mapper#update. Adds the updated Record to the store.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

id String | Number

Passed to Mapper#update.

record Object

Passed to Mapper#update.

opts Object <optional>

Passed to Mapper#update. See Mapper#update for more configuration options.

Fires:
Return value:
Type Description
Promise

Resolves with the result of the update.

Details
Since Source
3.0.0 SimpleStore.js, line 1681
Inherited From:
Example
import {SimpleStore} from 'js-data'
import {HttpAdapter} from 'js-data-http'

const store = new SimpleStore()
store.registerAdapter('http', new HttpAdapter(), { default: true })

store.defineMapper('post')

// Since this example uses the http adapter, we'll get something like:
//
//   PUT /post/1234 {"status":"published"}
store.update('post', 1, { status: 'published' }).then((post) => {
  // The post record has also been updated in the in-memory store
  console.log(store.get('post', 1234))
})

updateAll(name, props, query, opts)

Wrapper for Mapper#updateAll. Adds the updated Records to the store.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

props Object

Passed to Mapper#updateAll.

query Object <optional>

Passed to Mapper#updateAll.

opts Object <optional>

Passed to Mapper#updateAll. See Mapper#updateAll for more configuration options.

Fires:
Return value:
Type Description
Promise

Resolves with the result of the update.

Details
Since Source
3.0.0 SimpleStore.js, line 1773
Inherited From:
Example
import {SimpleStore} from 'js-data'
import {HttpAdapter} from 'js-data-http'

const store = new SimpleStore()
store.registerAdapter('http', new HttpAdapter(), { default: true })

store.defineMapper('post')

// Since this example uses the http adapter, we'll get something like:
//
//   PUT /post?author_id=1234 {"status":"published"}
store.updateAll('post', { author_id: 1234 }, { status: 'published' }).then((posts) => {
  // The post records have also been updated in the in-memory store
  console.log(store.filter('posts', { author_id: 1234 }))
})

updateMany(name, records, opts)

Wrapper for Mapper#updateMany. Adds the updated Records to the store.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

records Array.<Object> | Array.<Record>

Passed to Mapper#updateMany.

opts Object <optional>

Passed to Mapper#updateMany. See Mapper#updateMany for more configuration options.

Fires:
Return value:
Type Description
Promise

Resolves with the result of the update.

Details
Since Source
3.0.0 SimpleStore.js, line 1863
Inherited From:
Example
import {SimpleStore} from 'js-data'
import {HttpAdapter} from 'js-data-http'

const store = new SimpleStore()
store.registerAdapter('http', new HttpAdapter(), { default: true })

store.defineMapper('post')

// Since this example uses the http adapter, we'll get something like:
//
//   PUT /post [{"id":3,status":"published"},{"id":4,status":"published"}]
store.updateMany('post', [
  { id: 3, status: 'published' },
  { id: 4, status: 'published' }
]).then((posts) => {
  // The post records have also been updated in the in-memory store
  console.log(store.getAll('post', 3, 4))
})

validate(name, records, opts)

Wrapper for Mapper#validate.

Method parameters:
Name Type Argument Description
name String

Name of the Mapper to target.

records Array.<Object> | Array.<Record>

See Mapper#validate.

opts Object <optional>

See Mapper#validate.

Return value:
Type Description
Promise

See Mapper#validate.

Details
Since Source See
3.0.0 Container.js, line 881
Inherited From:
Example
import {Container} from 'js-data'
const store = new Container()
store.defineMapper('post', {
  schema: {
    properties: {
      name: { type: 'string' },
      id: { type: 'string' }
    }
  }
})
let errors = store.validate('post', { name: 'John' })
console.log(errors) // undefined
errors = store.validate('post', { name: 123 })
console.log(errors) // [{ expected: 'one of (string)', actual: 'number', path: 'name' }]

Events


add

Fired when one or more records are added to the in-memory store. See SimpleStore~addListener on how to listen for this event.

Inherited From:

afterCreate

Fired during SimpleStore#create. See SimpleStore~afterCreateListener for how to listen for this event.

Inherited From:

afterCreateMany

Fired during SimpleStore#createMany. See SimpleStore~afterCreateManyListener for how to listen for this event.

Inherited From:

afterDestroy

Fired during SimpleStore#destroy. See SimpleStore~afterDestroyListener for how to listen for this event.

Inherited From:

afterDestroyAll

Fired during SimpleStore#destroyAll. See SimpleStore~afterDestroyAllListener for how to listen for this event.

Inherited From:

afterFind

Fired during SimpleStore#find. See SimpleStore~afterFindListener for how to listen for this event.

Inherited From:

afterFindAll

Fired during SimpleStore#findAll. See SimpleStore~afterFindAllListener for how to listen for this event.

Inherited From:

afterUpdate

Fired during SimpleStore#update. See SimpleStore~afterUpdateListener for how to listen for this event.

Inherited From:

afterUpdateAll

Fired during SimpleStore#updateAll. See SimpleStore~afterUpdateAllListener for how to listen for this event.

Inherited From:

afterUpdateMany

Fired during SimpleStore#updateMany. See SimpleStore~afterUpdateManyListener for how to listen for this event.

Inherited From:

beforeCreate

Fired during SimpleStore#create. See SimpleStore~beforeCreateListener for how to listen for this event.

Inherited From:

beforeCreateMany

Fired during SimpleStore#createMany. See SimpleStore~beforeCreateManyListener for how to listen for this event.

Inherited From:

beforeDestroy

Fired during SimpleStore#destroy. See SimpleStore~beforeDestroyListener for how to listen for this event.

Inherited From:

beforeDestroyAll

Fired during SimpleStore#destroyAll. See SimpleStore~beforeDestroyAllListener for how to listen for this event.

Inherited From:

beforeFind

Fired during SimpleStore#find. See SimpleStore~beforeFindListener for how to listen for this event.

Inherited From:

beforeFindAll

Fired during SimpleStore#findAll. See SimpleStore~beforeFindAllListener for how to listen for this event.

Inherited From:

beforeUpdate

Fired during SimpleStore#update. See SimpleStore~beforeUpdateListener for how to listen for this event.

Inherited From:

beforeUpdateAll

Fired during SimpleStore#updateAll. See SimpleStore~beforeUpdateAllListener for how to listen for this event.

Inherited From:

beforeUpdateMany

Fired during SimpleStore#updateMany. See SimpleStore~beforeUpdateManyListener for how to listen for this event.

Inherited From:

change

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

Inherited From:

remove

Fired when one or more records are removed from the in-memory store. See SimpleStore~removeListener for how to listen for this event.

Inherited From: