Skip to content
Joe Minichino edited this page Aug 16, 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

If you're working in a node.js environment, run npm install lokijs and make sure to call var loki = require('lokijs')

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.insert( { name : 'odin', email: 'odin.soap@lokijs.org', age: 38 } );
var thor = users.insert( { name : 'thor', email : 'thor.soap@lokijs.org', age: 25 } );
var stan = users.insert( { name : 'stan', email : 'stan.soap@lokijs.org', age: 29 } );
var oliver = users.insert( { name : 'oliver', email : 'oliver.soap@lokijs.org', age: 31 } );
var hector = users.insert( { name : 'hector', email : 'hector.soap@lokijs.org', age: 15} );
var achilles = users.insert( { name : 'achilles', email : 'achilles.soap@lokijs.org', 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);