0
var db = new Dexie(app.settings.unpublishedBooksDb);
db.version(1).stores({
    friends: "++id,name,shoeSize"
});
db.open();
db.close();

I have a precreated indexedDB database using the code above, and then on another view in the application, I need to add a row to a table.

var db = new Dexie('myDb');
db.open().then(function() {
    console.log ('opened'); //this works
    db.friends.add({name:"Fredrik"}); //this doesnt do anything and adding a catch doesn't throw an error either
}).finally(function () {
    db.close();
});

I tried using .transaction but still the same. If I try using Chrome's console, I get an error : Cannot read property add of undefined

Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75
Omer S
  • 71
  • 5

1 Answers1

0

your second db instance contains no info about what tables it would contain. So the implicit table property (db.friends) is not there. What actually happens is that it throws TypeError: cannot read property 'add' of undefined. If you would catch the call (not just do a finally), you would get that TypeError catched.

What you can do is to reference the friends table by db.table('friends').add ({name: 'Fredrik'}) instead of db.friends.add({name: 'Fredrik'}).

Beware though that defining the database without specifying table schema is not as thorowgly tested and used, so I would recommend using it with a schema defined to avoid other pitfalls as well. If you for architectural reasons still need to do it your way, be aware that transaction scopes works a little different since you cannot use the dynamic implicit tale properties in the transaction scopes either and db.table() currently does not return a transaction-bound Table instance if you are in a transaction scope. You would have to use the old transaction API:

db.transaction('rw', 'friends', function (friends, trans) {
    friends.put({name: 'Fredrik'});
});

...instead of:

db.transaction('rw', 'friends', function () {
    db.friends.put({name: 'Fredrik'});
});

Best wishes, David

David Fahlander
  • 5,058
  • 1
  • 20
  • 19
  • Thanks David, that does the job! I just have to create my own method that opens the db after defining the same schema each time I need to – Omer S May 14 '15 at 12:12
  • Unless there are other good reasons (I don't say there couldn't be), I would suggest to having the db defined in a single place and always use the same instance. Even though it defines the schema on an already opened database, that does not harm - it wont try to recreate the indexes - it will find out whether the db is created or not and only create tables and indexes if needed. If you use several db instances, make sure to close them when done. Otherwise you'll have db connections that may block another db from upgrading or being deleted. – David Fahlander May 19 '15 at 11:34