Search code examples
dexie

Passing Dexie collection from variable


I have this code (Indexeddb/Dexie)

db1.RestrictionsImport.where('idx').equals(n).toArray().then(function(x){...})

This works fine but I have an multitude of collections with "Restrictions" for which I have to perform the search(es). If I do this:

var collection= ['RestrictionsImport','RestrictionsPrice','RestrictionsCountry','RestrictionsPart',...etc]
db1.collection[0].where('idx').equals(n).toArray().then(function(x){...})

It crashes:

index.html:251 Uncaught TypeError: Cannot read property 'where' of undefined at index.html:251   (anonymous) @ index.html:251

This series of restriction types can count from a few to dozens depending on other queries so I have to put the Dexie queries in a loop, I cannot simply write them one after another...

Some suggestions ?

Thanks in advance, H.D.


Solution

  • Yes. db.tables is the property to access in order to get an array of the defined tables:

    db.tables.forEach(table => {
        console.log(table.name);
    });
    

    A table is an instance of Dexie.Table

    If you for example need to put a new item into each table, do:

    Promise.all(db.tables.map(table => table.put(newItem)))
      .then(...)
      .catch(...)
    

    The above code also possible to use within a transaction:

    db.transaction('rw', db.tables, () => {
      return Dexie.Promise.all(db.tables.map(table => {
        return table.put(newItem);
      }));
    }).then({
      ...
    }).catch({
      ...
    });