LokiJS In-Memory Database

1.5.12 · maintenance · verified Sun Apr 19

LokiJS is a fast, document-oriented JavaScript in-memory database designed for various environments including browsers, Node.js, and NativeScript. It functions by storing JavaScript objects as documents in a NoSQL fashion, enabling high-performance retrieval through indexing and dynamic views. Currently at version 1.5.12, its release cadence appears infrequent, with the last major update several years ago. Key differentiators include its small footprint, suitability for client-side session stores, and built-in persistence adapters (like localStorage, IndexedDB, or filesystem) that can be extended with custom solutions. It prioritizes speed by maintaining unique and binary indexes and offering dynamic views for frequently accessed data subsets, making it ideal for performance-critical applications where data can reside primarily in memory.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a LokiJS in-memory database, configure it with the LocalStorage adapter for persistence, add a collection with a unique constraint, insert documents, and perform basic queries and updates. It includes an `autoload` and `autosave` setup to manage data lifecycle across sessions.

import Loki from 'lokijs';
import LokiLocalStorageAdapter from 'lokijs/src/loki-local-storage-adapter';

const dbName = 'myCoolDatabase.db';
const adapter = new LokiLocalStorageAdapter(dbName);

const db = new Loki(dbName, {
  adapter: adapter,
  autoload: true,
  autoloadCallback: databaseInitialize,
  autosave: true,
  autosaveInterval: 4000
});

function databaseInitialize() {
  let users = db.getCollection('users');
  if (users === null) {
    users = db.addCollection('users', { unique: ['email'] });
  }

  // Check if there's any data, if not, insert some
  if (users.count() === 0) {
    users.insert({ name: 'Alice', email: 'alice@example.com', age: 30 });
    users.insert({ name: 'Bob', email: 'bob@example.com', age: 24 });
    console.log('Initial data inserted.');
  } else {
    console.log('Database already contains data.');
  }

  const allUsers = users.find();
  console.log('All users:', allUsers);

  const youngUsers = users.find({ age: { '$lt': 25 } });
  console.log('Users younger than 25:', youngUsers);

  // Update an existing user
  const alice = users.findOne({ name: 'Alice' });
  if (alice) {
    alice.age = 31;
    users.update(alice);
    console.log('Alice updated:', users.findOne({ name: 'Alice' }));
  }

  // Ensure data is saved after modifications if autosave is off or before manual exit
  // db.saveDatabase(); // Autosave handles this in this example
}

console.log('LokiJS database initialized or loaded.');

view raw JSON →