2016年5月19日 星期四

Basic CRUD operations in LokiJS

LokiJS (http://lokijs.org/#/) is a lightweight JavaScript in-memory database.

Installation

nam install lokijs --save

Initial Database

Basic
var db = new lokijs('db.json');
The db.json will be created in the <root> folder, i.e. <root>/db.json.
Custom path
var path = require('path');
var db = new lokijs(path.join(__dirname, '..', 'data', 'db.json'));
The db.json will be created in the <root>/data folder, i.e. <root>/data.db.json.

Initial Collection

var info = db.getCollection('info');
if(!info){
  info = db.addCollection('info');
}  
First, getCollection() by collection name 'info', and check if the collection exists. If the collection does not exist, then create a collection by addCollection() with collection name 'info'.

CRUD operations

Create
info.insert({
  name: 'phchu',
  age: 18
});
Read
var user = info.findObject({'name':'phchu'});
The return result user is an object, that you can get other attributes by dot, e.g. user.age to get the phchu's age. The findObject() is not the only operation to query result from database, you can reference the API document (http://lokijs.org/#/docs#find) for details.
Update
user.age = 30;
info.update(user);
Delete
info.remove(user);

Final step: Save

db.saveDatabase();

Load database

db.loadDatabase({}, function () {
var info = db.getCollection('info');
console.log('Info: ', info.data);
}); 

Put them together

function lokijsCRUD() {
  var info; 
  db.loadDatabase({}, function () {
    //Initial collection
    info = db.getCollection('info');
    if(!info)
      info = db.addCollection('info');
    console.log('Initial info: ', info.data);
    //Create a user info    
    info.insert({name: 'phchu',
                    age: 18});
    console.log('Add a user: ', info.data);
    //Read user's age  
    var user = info.findObject({'name':'phchu'});
    console.log('User '+user.name+' is '+ user.age +' years old.');
    //Update user's age
    user.age = 30;
    info.update(user);
    console.log('User '+user.name+' is '+ user.age +' years old.');
    //Delete the user
    info.remove(user);
    console.log('Collection info: ', info.data);
    //Save
    profilesDB.saveDatabase();               
  });        
}

Result

Initial info: []
Add a user: [ { name: 'phchu',
age: 18,
meta: { revision: 0, created: 1463638026851, version: 0 },
'$loki': 1 } ]
User phchu is 18 years old.
User phchu is 30 years old.
Collection info: []
技術提供:Blogger.