Dexie.on.populate-(old-version)

Syntax

db.on("populate", function (transaction) {});

Parameters

transaction: Transaction

Transaction object to work with

Description

The populate event occurs only once in a database' lifetime - in case the database was not present on the client when db.open() was called, and the object stores was needed to be created.

When upgrading database, on("populate") will NOT be called since it was already called before when database was created in the previous version. In case you change the code that subscribes to the populate event between versions, you should add an upgrade function to the new version that upgrades earlier populated data.

The populate event is fired during an onupgradeneeded event and before db.open() has been successfully committed. In case an exception is thrown or an error event happens during the populate event, the entire database creation will be aborted and db.open() will fail.

Sample

var db = new Dexie("MyDB");
db.version(1).stores({friends: "id++,name,gender"});
db.on("populate", function() {
    db.friends.add({name: "Josephina", gender: "unisex"});
});
db.open();

Limitations

The transaction instance given to callback is an upgrade transaction and as all IndexedDB transactions, it will commit as soon as you stop using it. This means that if you call other async APIs, such as ajax calls or setTimeout(), the transaction object will automatically commit and you cannot continue populate data using that transaction.

If your aim is to populate the database from an ajax- or other asynchronous request, you can do so by using the on('ready') event rather than on('populate'). See a working (and fully tested) sample below:

Ajax Populate Sample

This sample shows how to populate your database from an ajax call. Note that on('populate') is not suitable for that and instead we are using on('ready'):

Same Sample with Comments And Logging

Console Output on first run:

Console Output when data is already populated:

Watch the full HTML source, or view it in your browser

See Also

The Populate Event