Reputation: 13843
Using IndexedDB when my app first runs I populate it with some data, I want to ensure that when the database and tables are created that they do not already exists.
Can I query the length of a table to see if it contains and data in JavaScript?
Upvotes: 6
Views: 13460
Reputation: 600
We can use the objectStoreNames property of IndexDB to check the existence of an ObjectStore.
var db_object, object_store;
if( !db.objectStoreNames.contains(currentobjectstore) )
{
db_object = i_db.createObjectStore(currentobjectstore, {autoIncrement:true} );
object_store = db.transaction(currentobjectstore, 'readwrite').objectStore(currentobjectstore);
} else {
object_store = db.transaction(currentobjectstore, 'readwrite').objectStore(currentobjectstore);
}
Upvotes: 8
Reputation: 71
Best way is trying to open objectStore in try catch block. It is synchronous also. In case of an error you can create store for example:
var store;
try {
store = request.transaction.objectStore('yourStore');
}
catch(e) {
store = db.createObjectStore('yourStore');
}
Upvotes: 6
Reputation: 365
The database is created if a database with the specified name does not exist else it opens it
eg.var request = indexedDB.open("DataTbl");
So if your db already exists it will just open it and about you checking if the contents in the table already exists then you can make an xyz objectstore and store some key/value flag pair inside it saying that the insertion was successful and check it later everytime when page is reloaded.
Also you can give at try to count function specified by @toske
ref :
Upvotes: -1
Reputation: 1754
You can use objectStore.count() function, but i recommend storing some kind of meta-data that would say that your local db is initialized. Otherwise, you can have page-reload in middle of data creation and never have your data fully synced with remote data.
Upvotes: 1