2

I'm fair new to indexedDB (IDB) and trying to work on CRUD using jakearchibald's IndexedDB Promised API . I can able to create database and objectStore and indexes as well

Creating database

createEmptyDB: function () {
    return new Promise( function (resolve) {
      idb.open( IDB.dbName, 1, function (idbCx) {
      }).then( resolve)
      .catch( function (err) {
      reject( err);
    });
    });
  }

I have created the table books and indexes title and year.

Creating table/objectStore and indexes

createTableAndIndex: function (tableName) {
    return new Promise( function (resolve) {
      idb.open( IDB.dbName, 2, function (idbCx) {
        if (!idbCx.objectStoreNames.contains(tableName)) {
          bookssOS = idbCx.createObjectStore(tableName, {keyPath:"id",autoIncrement:true,});
          bookssOS.createIndex('title', 'title', {unique: false});
          bookssOS.createIndex('year', 'year', {unique: false});
        }

      }).then( resolve);
    });
  }

I have created the cursor to fetch the data matches the book title name as 'Book6'

Cursor to iterate the values from the table books

fetchUsingCursor: function ( tableName) {
  return new Promise( function (resolve, reject) {
    idb.open( IDB.dbName).then( function (idbCx) {  // idbCx is a DB connection
      var tx = idbCx.transaction('books', 'readonly');
      var store = tx.objectStore('books');

      var storeIndex = store.index('title');
      var range = IDBKeyRange.only("Book6");

     // var storeIndex = store.index('year');
     // var range = IDBKeyRange.only(2000);

      return storeIndex.openCursor(range);
    }).then(function bookItems(cursor) {
      if (!cursor) {
        return;
      }

      for (var field in cursor.value) {
        console.log(cursor.value['title']);
      }
      return cursor.continue().then(bookItems);
    })
    .catch( function (err) {
      reject( err);
    });
  });
}

But when i try to fetch the books by matching year '2000' by commenting the index title and enable year index, it did not fetch the books added with year 2000 as the record follows. Please help me to find the issue and thanks in advance.

"books":[
        {id: "006251587X", title: "Book1", year: 2000, edition: 2},
        {id: "0465026567", title: "Book2", year: 2000, edition: 3},
        {id: "0465030793", title: "Book3", year: 1990,  edition: 4},
        {id: "0465030794", title: "Book4", year: 2000,  edition: 4},
        {id: "0465030795", title: "Book5", year: 2000,  edition: 4},
        {id: "0465030796", title: "Book6", year: 1990,  edition: 4}
      ]
SeekeR
  • 145
  • 1
  • 7

0 Answers0