javascriptjsondatabaselokijsnosql

Unable to save db with lokiJS as json file


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.


Solution

  • 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();
    });