2

All:

I am pretty new to Lokijs, I wonder how can I reload the database and collection which has been persisted?

Say that I build a database and collection, then I persist it( like click a button to trigger persistence process):

    var db = new Loki("mydb");
    var users = db.addCollection('users');
    // we bind this to a button click event
    function saveUser(){
        users.insert({
          name: 'joe'
        });
        users.insert({
          name: 'john'
        });
        users.insert({
          name: 'jack'
        });
        db.saveDatabase();
    }

Then when I refresh this page, how can I load "mydb" and "users" from persistence rather than create new one( cos it will go thru var db = new Loki("mydb"); again ), is there API to check if a database exists?

Thanks

Lawrence Nwoko
  • 79
  • 1
  • 10

1 Answers1

3

This is a common question, the default way is to use the loadHandler, like illustrated here. Basically you have to pass a loadHandler function that initializes the db based on an existing file:

var db = new loki('test', 
      {
        autoload: true,
        autoloadCallback : loadHandler,
        autosave: true, 
        autosaveInterval: 10000
      }); 
var users = null;
function loadHandler() {
    users = db.getCollection('users');
    if (!users) {
        users = db.addCollection('users');
    }
}

Hope this helps.

Joe Minichino
  • 2,793
  • 20
  • 20