Skip to content
Joe Minichino edited this page Jul 29, 2013 · 27 revisions

LokiJS

Overview

LokiJS is a document oriented javascript database, somewhat similar to MongoDB. It supports indexing, querying and filtering of data collections. LokiJS also supports more advanced features such as mapReduce, transactions and lets you implement custom remote synchronization to save data to a server (or a local file on mobile).

Features

1. Document oriented

Javascript "speaks" JSON, so data is stored in as JSON objects.

2. Indexing

You can specify indexes to speed searches on certain object properties.

3. Views

You can declare custom view functions to return result sets based on complex logic.

4. Map reduce

You can declare map and reduce functions to retrieve aggregate data from your database.

Example usage

Creating the db:

var db = new loki('Example');

Create a collection, specifying name, Type, index fields and whether the collection is transactional:

var users = db.addCollection('users','User', ['email'], true);

Note that indexes and transactional flag are optional parameters.

Add a bunch of users in the database:

    var odin = users.document( { name : 'odin', email: '[email protected]', age: 38 } );
    var thor = users.document( { name : 'thor', email : '[email protected]', age: 25 } );
    var stan = users.document( { name : 'stan', email : '[email protected]', age: 29 } );
    var oliver = users.document( { name : 'oliver', email : '[email protected]', age: 31 } );
    var hector = users.document( { name : 'hector', email : '[email protected]', age: 15} );
    var achilles = users.document( { name : 'achilles', email : '[email protected]', age: 31 } );

Operate an update:

stan.name = 'Stan Laurel';
// update object (this really only syncs the index)
users.update(stan);

Create views:

function ageView(obj){
  return obj.age > 30;
}
// a little more complicated, users with names longer than 3 characters and age over 30
function aCustomFilter(obj){
  return obj.name.length  < 5 && obj.age > 30;
}

// test the filters
var result = users.view(ageView);

var anotherResult = users.view(aCustomFilter);