3

I'm testing LokiJS in my browser. I want to save the db created as json file in same folder. But nothing happens. This is the code that i found online and i'm testing:

var db = new loki('test.json');
var db2 = new loki('test.json');

var users = db.addCollection('users');
users.insert({
    name: 'joe'
});
users.insert({
    name: 'john'
});
users.insert({
    name: 'jack'
});
console.log(users.data);
db.saveDatabase();

db2.loadDatabase({}, function () {
    var users2 = db2.getCollection('users')
    console.log(users2.data);
});

What am i missing ? Thanks.

Community
  • 1
  • 1
Mr.M
  • 135
  • 2
  • 12

1 Answers1

4

Yeah it's a bit tricky

You have to load a database before using it or it will erase with an empty one. Here is a little script that allows you to load a collection or create one if it does not exist + saving the changes

var loki = require('lokijs'),
    db = new loki('test.json');

function loadCollection(colName, callback) {
    db.loadDatabase({}, function () {
        var _collection = db.getCollection(colName);

        if (!_collection) {
            console.log("Collection %s does not exit. Creating ...", colName);
            _collection = db.addCollection('users');
        }

        callback(_collection);
    });
}

loadCollection('users', function (users) {
    //show the users
    console.log(users.data);

    var newUser = {
        name: 'user_' + (new Date()).getTime()
    };

    //add one
    users.insert(newUser);

    console.log("Added a new user => ", newUser);

    //save 
    db.saveDatabase();
});
Ezkin
  • 101
  • 3
  • Seems like what i wanted to do isn't possible. I wanted to load and save the json file to filesystem using javascripts, creating an app to use only offline. By what i understood, javascript doen't allow that, and i've to use nodejs. Am i right ? – Mr.M Oct 26 '16 at 08:51
  • Yeah. The filesystem is pretty unreachable from a browser. If you want to create an offline application without any server communication, you should look into locastorage. I think lokiJS emplements it by it's fairly new. [Look here for more information](https://github.com/techfort/LokiJS/wiki/LokiJS-persistence-and-adapters) – Ezkin Oct 26 '16 at 11:36
  • When you are loading the db, `db.loadDatabase({}, function () { var _collection = db.getCollection(colName); if (!_collection) { console.log("Collection %s does not exit. Creating ...", colName); _collection = db.addCollection('users'); } callback(_collection); }); }` What does it mean by the statement loadDatabase({}) - I don't understand what the empty paranthesis mean!! Are we making the db empty there? or the collections empty? Please help. @Ezkin – lakshman_dev Dec 20 '17 at 09:13