Data Store

The content in this guide refers to the newly released version 3 of the library. You can still access the version 1.x guides here.

Version 1.x is now deprecated. We will continue to support 1.x through March 31, 2017 (End of Support - EOS). If you are currently using 1.x in your apps, you will need to upgrade your apps to 3.x before the EOS date. We have created a migration guide to help you.

The simplest use case of Kinvey is storing and retrieving data to and from your cloud backend.

The basic unit of data is an entity and entities of the same kind are organized in collections. An entity is a set of key-value pairs which are stored in the backend in JSON format. Kinvey's libraries automatically translate your native objects to JSON.

Kinvey's data store provides simple CRUD operations on data, as well as powerful filtering and aggregation.

Each DataStore in your application represents a collection on your backend. Create a DataStore to start working with the data in a collection.

var dataStore = Kinvey.DataStore.collection('collection-name');

Through the remainder of this guide, we refer to the instance we just retrieved as dataStore.

By default, the library creates a DataStore of type Cache. To understand the types of datastores and when to use each type, please refer to the section on DataStore Types

Entities

The Kinvey service has the concept of entities, which represent a single resource.

{
    _id: 'entity-id',
    key1: 'value1',
    key2: 'value2'
    ...
}

The library does not provide any built-in classes to represent entities. There are a large variety of third party JavaScript libraries which do provide this, and most of them will accept object literals as entity attributes.

Saving

You can save an entity by calling dataStore.save.

var promise = dataStore.save({
  _id: 'optional-id',
  field: 'value'
}).then(function onSuccess(entity) {
  // ...
}).catch(function onError(error) {
  // ...
});

The library uses the _id property of the entity to distinguish between updates and inserts.

  • If the entity has an _id, the library treats it as an update to an existing entity.

  • If the entity does not have an _id, the library treats it as a new entity. The Kinvey backend assigns an automatic _id for a new entity.

Fetching

You can retrieve entities by either looking them up using an id, or by querying a collection.

The Kinvey JavaScript Library uses the observable pattern to return data on find operations. APIs that fetch data require the application to register a subscriber that gets invoked when data is available. We use Observables to accomplish this.

When data is retrieved from multiple sources (i.e. cache and backend), the subscriber gets invoked multiple times - first with the results from the cache; then with the results from the backend.

Fetching by Id

To fetch an (one) entity by id, call dataStore.findById.

var stream = dataStore.findById('entity-id');
stream.subscribe(function onNext(entity) {
  // ...
}, function onError(error) {
  // ...
}, function onComplete() {
  // ...
});

Fetching by Query

To fetch all entities in a collection, call dataStore.find.

var stream = dataStore.find();
stream.subscribe(function onNext(entities) {
  // ...
}, function onError(error) {
  // ...
}, function onComplete() {
  // ...
});

To fetch multiple entities using a query, call dataStore.find and pass in a query.

var query = new Kinvey.Query();
query.equalTo('field', 'value');
var stream = dataStore.find(query);
stream.subscribe(function onNext(entities) {
  // ...
}, function onError(error) {
  // ...
}, function onComplete() {
  // ...
});

Deleting

To delete an entity, call dataStore.removeById and pass in the entity _id.

var promise = dataStore.removeById('entity-id')
promise = promise.then(function onSuccess(result) {
  // ...
}).catch(function onError(error) {
  // ...
});

Deleting Multiple Entities at Once

To delete multiple entities at once, call dataStore.remove. Optionally, you can pass in a query to only delete entities matching the query.

var query = new Kinvey.Query();
query.equalTo('property', 'value');

var promise = dataStore.remove(query)
promise = promise.then(function onSuccess(result) {
  // ...
}).catch(function onError(error) {
  // ...
});

Metadata

Every entity has metadata associated with it. The metadata is accessible through the entities _kmd property. Alternatively, you can use the Kinvey.Metadata class to easily extract this metadata.

var entity = {
  _id: 'entity-id',
  _acl: { /*ACL*/ },
  _kmd: { /*Metadata*/ },
  prop: 'value'
}
var metadata = new Kinvey.Metadata(entity);

The following properties are exposed on the metadata object:

  • metadata.createdAt returns the Date when the entity was created on Kinvey.
  • metadata.lastModified returns the Date when the entity was last updated on Kinvey.

Querying

The Kinvey.Query class allows you to build queries for use in collections. An empty query, by default, matches all models in a collection.

var query = new Kinvey.Query();

Operators

All operator methods as exposed by Kinvey.Query follow the same pattern: the first argument must be the field under condition, while the other arguments specify the exact condition on that field. All operators return the query itself, so it is easy to concatenate multiple conditions on one line.

For example, to select all models with a rate between 25 and 50:

var query = new Kinvey.Query();
query.greaterThanOrEqualTo('rate', 25).lessThanOrEqualTo('rate', 50);

Comparison Operators

  • equalTo matches if the field is = the supplied value.
  • greaterThan matches if the field is > the supplied value.
  • greaterThanOrEqualTo matches if the field is >= the supplied value.
  • lessThan matches if the field is < the supplied value.
  • lessThanOrEqualTo matches if the field is <= the supplied value.
  • notEqualTo matches if the field is != the supplied value.
  • exists matches if the field exists.
  • mod matches if the field modulo the supplied divisor (second argument) has the supplied remainder (third argument).
  • matches matches if the field matches the supplied regular expression.

Regular expressions need to be anchored (prefixed with ^), and case sensitive. To do case insensitive search, create a normalized (i.e. all lowercase) field in your collection and perform the match on that field.

Array Operators

  • contains matches if any of the supplied values is an element in the field.
  • containsAll matches if the supplied values are all elements in the field.
  • notContainedIn matches if the supplied value is not an element in the field.
  • size matches if the number of elements in the field equals the supplied value.

Modifiers

Query modifiers control how query results are presented. A distinction is made between limit, skip, and sort modifiers.

Limit and Skip

Limit and skip modifiers allow for paging of results. Set the limit to the number of results you want to show per page. The skip modifier indicates how many results are skipped from the beginning.

// Show results 20–40
var query = new Kinvey.Query();
query.limit = 20;
query.skip = 20;

Sort

Query results are sorted either in ascending or descending order. It is possible to add multiple fields to sort on.

// Sort on last name (ascending), then on age (descending).
var query = new Kinvey.Query();
query.ascending('last_name');
query.descending('age');

Data is sorted lexicographically, meaning B comes before a, and 10 before 2.

Field Selection

By default, all fields in an entity will be retrieved. You can, however, specify specific fields to retrieve. This can be useful to save bandwidth.

var query = new Kinvey.Query();
query.fields = [ 'last_name', 'age' ];

Saving documents after retrieving them using Field Selection will result in the loss of all fields not selected.

Compound Queries

You can combine filters with modifiers within a single query.

// Returns the first five users with last_name “Doe”, sorted by first_name.
var query = new Kinvey.Query();
query.limit = 5;
query.equalTo('last_name', 'Doe');
query.ascending('first_name');

Joining Operators

It is very easy to join multiple queries into one. In order of precedence, the three joining operators are listed below in order of precendence.

  • and joins two or more queries using a logical AND operation.
  • nor joins two or more queries using a logical NOR operation.
  • or joins two or more queries using a logical OR operation.

The example below demonstrates how to join two separate queries.

var query = new Kinvey.Query();
query.equalTo('last_name', 'Doe');
var secondQuery = new Kinvey.Query();
secondQuery.equalTo('last_name', 'Roe')

// Selects all users with last_name “Doe” or “Roe”.
query.or(secondQuery);

Alternatively, the snippet above can be shortened using the join operator inline.

// Selects all users with last_name “Doe” or “Roe”.
var query = new Kinvey.Query();
query.equalTo('last_name', 'Doe').or().equalTo('last_name', 'Roe');

You can build arbitrary complex queries using any join operators. The rule of thumb is to take the precendence order into account when building queries to make sure the correct results are returned.

Counting

To count the number of entities in a collection, call dataStore.count. Optionally, you can pass in a query to only count the entities matching the query.

Aggregation/Grouping

Grouping allows you to collect all entities with the same value for a field or fields, and then apply a reduce function (such as count or average) on all those items.

The results are returned as an object literal that represents the list of groups containing the result of the reduce function.

For example, let’s group a collection of companies based on the year they launched.

var promise = dataStore.group('companies', Kinvey.Aggregation.count('launched'));
promise.then(function(result) {
    ...
);

Reduce Function

There are five pre-defined reduce functions.

  • Kinvey.Aggregation.count counts the number of elements in the group.
  • Kinvey.Aggregation.sum sums together the numeric values of the supplied field.
  • Kinvey.Aggregation.min finds the minimum of the numeric values of the supplied field.
  • Kinvey.Aggregation.max finds the maximum of the numeric values of the supplied field.
  • Kinvey.Aggregation.average finds the average of the numeric values of the supplied field.

Scoping With Queries

Groups can also take an optional condition. This is a query that acts as a filter that is applied on the server before the reduce function is evaluated. Any limit, skip, and sort modifiers are applied after the reduce function is evaluated.

In our above example, assume we wanted to group only the companies who have offices in Boston. In addition, we want to order the resulting groups by the year they launched and only display the first two. It would look like:

// Build the query and group.
var query = new Kinvey.Query();
query.equalTo('city', 'Boston');
query.ascending('launched')
query.limit = 2;

var group = Kinvey.Aggregation.count('launched');
group.query(query);

var promise = dataStore.group('companies', group);
promise.then(function(result) {
    ...
);

Location Querying

See the Location guide for information on how to query data by location.

DataStore Types

A key aspect of good mobile apps is their ability to render responsive UIs, even under conditions of poor or missing network connectivity. The Kinvey library provides caching and offline capabilities for you to easily manage data access and synchronization between the device and the backend.

Kinvey’s DataStore provides configuration options to solve common caching and offline requirements.

When you get an instance of a datastore in your application, select which scenario from the following list most closely resembles your data requirements:

  1. You want a copy of some (or all) the data from your backend to be available locally on the device and you'd like to sync it periodically with the backend then you would use DataStoreType.Sync

  2. You want data stored on the device to optimize your app’s performance and/or provide offline support for short periods of network loss then you would use DataStoreType.Cache

  3. You want the data in your backend to never be stored locally on the device, even if it means that the app cannot support offline usage then you would use DataStoreType.Network

Sync

Configuring your datastore as a Sync datastore allows you to pull a copy of your data to the device and work with it completely offline. The library provides APIs to synchronize local data with the backend.

This type of datastore is ideal for apps that need to work for long periods without a network connection.

Here is how you'd use a Sync store -

// Get an instance
var dataStore = Kinvey.DataStore.collection('books', Kinvey.DataStoreType.Sync);

// Pull data from the backend and save it to the cache.
var promise = dataStore.pull().then(function onSuccess(entities) {
  // ...
}).catch(function onError(error) {
  // ...
});

// Find entities in the cache.
var stream = dataStore.find();
stream.subscribe(function onNext(data) {
  // ...
}, function onError(error) {
  // ...
}, function onCompleted() {
  // ...
});

// Save an entity to the cache. This entity can be synced with
// the backend at a later time.
var entity = {};
var promise = dataStore.save(entity);
promise = promise.then(function onSuccess(entity) {
  // ...
}).catch(function onError(error) {
  // ...
});

// Sync the data store with the backend.
// This will first push any pending local changes to the backend and
// then pull data from the backend and save it in the cache.
var promise = dataStore.sync();
promise = promise.then(function onSuccess(result) {
  // ...
}).catch(function onError(error) {
  // ...
});

The pull, push and sync APIs allow you to to synchronize data between the application and the backend. This section describes how these APIs work with examples.

Pull

Calling pull() retrieves data from the backend and stores it locally in the Sync Store.

By default, pulling will retrieve the entire collection to the device. Optionally, you can provide a query parameter to pull to restrict what entities are retrieved.

The pull API needs a network connection in order to succeed.

var dataStore = Kinvey.DataStore.collection('books', Kinvey.DataStoreType.Sync);

// Pull data from the backend and save it in the cache.
var promise = dataStore.pull();
promise = promise.then(function onSuccess(entities) {
  // ...
}).catch(function onError(error) {
  // ...
});

If your Sync Store has pending local changes, they must be pushed to the backend before pulling data to the store.

Push

Calling push() kicks off a uni-directional push of data from the library to the backend.

The library goes through the following steps to push entities modified in local storage to the backend -

  • Reads from the "pending writes queue" to determine what entities have been changed locally. The "pending writes queue" maintains a reference for each entity in local storage that has been modified by the app. For an entity that gets modified multiple times in local storage, the queue only references the last modification on the entity.

  • Creates a REST API request for each pending change in the queue. The type of request depends on the type of modification that was performed locally on the entity.

    • If an entity is newly created, the library builds a POST request.

    • If an entity is modified, the library builds a PUT request.

    • If an entity is deleted, the library builds a DELETE request.

  • Makes the REST API requests against the backend concurrently. Requests are batched to avoid hitting platform limits on the number of open network requests.

    • For each successful request, the corresponding reference in the queue is removed.

    • For each failed request, the corresponding reference remains persisted in the queue. The library adds information in the push/sync response to indicate that a failure occurred.

  • Returns a response to the application indicating the count of entities that were successfully synced, and a list of errors for entities that failed to sync.

var dataStore = Kinvey.DataStore.collection('books', Kinvey.DataStoreType.Sync);

// Push data from the cache that has changed to the backend.
// No data is retrieved from the backend.
var promise = dataStore.push();
promise = promise.then(function onSuccess(result) {
  // ...
}).catch(function onError(error) {
  // ...
});

Sync

Calling sync() on a Sync Store kicks off a bi-directional synchronization of data between the library and the backend. First, the library calls push to send local changes to the backend. Subsequently, the library calls pull to fetch data in the collection from the backend and stores it on the device.

You can provide a query as a parameter to the sync API, to restrict the data that is pulled from the backend. The query does not affect what data gets pushed to the backend.

var dataStore = Kinvey.DataStore.collection('books', Kinvey.DataStoreType.Sync);

// Sync the cache and backend.
var promise = dataStore.sync();
promise = promise.then(function onSuccess(result) {
  // ...
}).catch(function onError(error) {
  // ...
});


// Use a query to sync only a subset of data with the backend.
var query = new Kinvey.Query();
query.equalTo('field', 'value');

var promise = dataStore.sync(query);
promise = promise.then(function onSuccess(result) {
  // ...
}).catch(function onError(error) {
  // ...
});

Sync Count

You can retrieve a count of entities modified locally and pending a push to the backend.

// Number of entities modified offline.
var promise = dataStore.syncCount();
promise = promise.then(function onSuccess(count) {
  // ...
}).catch(function onError() {
  // ...
});

Cache

Configuring your datastore as a Cache datastore allows you to use the performance optimizations provided by the library. The library is smart enough to determine when to serve data from the cache and when to fetch it from the network. In addition, the cache allows you to work with data when the device goes offline.

This type of datastore is ideal for apps that are generally used with an active network, but may experience short periods of network loss.

Here is how you'd use a Cache store -

// Get an instance.
var dataStore = Kinvey.DataStore.collection('books', Kinvey.DataStoreType.Cache);

// Pull data from the backend and save it to the cache.
var promise = dataStore.pull().then(function onSuccess(entities) {
  // ...
}).catch(function onError(error) {
  // ...
});

// Fetch entities from both the cache and the backend
var stream = dataStore.find();
stream.subscribe(function onNext(entities) {
  // ...
}, function onError(error) {
  // ...
}, function onComplete() {
  // ...
});

// Save an entity.
// The entity will first be saved to cache and then to the backend.
// If you do not have a network connection, the entity will be stored in cache and can
// be synced with the backend at a later time.
var entity = {
  title: 'Mobile Library Development'
  author: 'Kinvey'
};

var promise = dataStore.save(entity);
promise = promise.then(function onSuccess(entity) {
  // ...
}).catch(function onError(error) {
  // ...
});

The Cache Store executes all CRUD requests against local storage as well as the backend. Any data retrieved from backend is stored in the cache. This allows the app to work offline by fetching data that has been cached from past usage.

The Cache Store also stores pending write operations when the app is offline. However, the developer is required to push these pending operations to the backend when the network resumes. The push API should be used to accomplish this.

Network

Configuring your datastore as Network turns off all caching in the library. All requests to fetch and save data are sent to the backend.

We don’t recommend this type of datastore for apps in production, since the app will not work without network connectivity. However, it may be useful in a development scenario to validate backend data without a device cache.

Here is how you would use a Network store -

// Get an instance
var dataStore = Kinvey.DataStore.collection('books', Kinvey.DataStoreType.Network);

// Fetch data from your backend
var stream = dataStore.find();
stream.subscribe(function onNext(entities) {
  // ...
}, function onError(error) {
  // ...
}, function onComplete() {
  // ...
});

// Save an entity to your backend.
var entity = {
  title: 'Mobile Library Development'
  author: 'Kinvey'
};

var promise = dataStore.save(entity);
promise = promise.then(function onSuccess(entity) {
  // ...
}).catch(function onError(error) {
  // ...
});
Got a question?