あるキーが含まれるデータのみ削除したいです。
createIndex()を使いキーを変更しており、そのあとopenCursor()でキーを指定したところ最初のデータのみ削除でき、その他のレコードは削除できずにnullが返ってきました。
その他のレコードも最初に取得できたデータとキーは一緒です。
回答をお願いします。
コード
function createDB() { var dbName = 'habitDB'; // DB名を指定して接続。指定したDB名がなければ新規作成。 var openDb = indexedDB.open( dbName ); // DBの更新時のみ実行 openDb.onupgradeneeded = function( event ) { var db = event.target.result; // テーブルを生成 db.createObjectStore( 'listTable', {keyPath: 'listId'} ); var weekStore = db.createObjectStore( 'weekDayTable', {keyPath: ['listId', 'weekId']} ); db.createObjectStore( 'recordTable', {keyPath: 'listId'} ); var monthStore = db.createObjectStore( 'monthTable', {keyPath: ['listId', 'month']} ); var toDoStore = db.createObjectStore( 'toDoTable', {keyPath: ['listId', 'toDoDate']} ); // index作成(引数1:名前, 引数2:キー名) toDoStore.createIndex( 'toDoStoreId', 'toDoDate',{unipue: false} ); weekStore.createIndex( 'weekStoreId', 'listId',{unipue: false} ); monthStore.createIndex( 'monthStoreId', 'listId', {unipue: false} ); alert( 'DBを更新しました。' ); // 接続解除 db.close(); } } /* keyが含まれるデータを削除する関数 */ // key: DBのキー name: createIndexの名前 table: DBのテーブル名 this.deleteOnly = function( key, name, table ) { return new Promise( function( resolve, reject ) { var dbName = 'habitDB'; var openDb = indexedDB.open( dbName ); openDb.onsuccess = function( event ) { var db = event.target.result; var transaction = db.transaction( table, 'readwrite' ); var store = transaction.objectStore( table ); var index = store.index( name ); index.getAll().onsuccess = function(event) { var test = event.target.result; for( var value of test ) { console.log(value); } } // データ範囲の指定 var cursor = index.openCursor( key, "next" ); cursor.onsuccess = function( event ) { var result = event.target.result; if( result ) { console.log("削除"); console.log(result.value); result.delete(); result.continue(); }else{ resolve(); } } }; }); }
データ例
listId | Date | flag |
---|---|---|
1 | 2019-01-01 | false |
1 | 2019-01-02 | false |
1 | 2019-01-03 | false |
1 | 2019-01-04 | false |
1 | 2019-01-05 | false |
2 | 2019-01-06 | false |
エラー例:キーを1で指定するとリストの一番上のレコードのみ削除されてしまう。
あなたの回答
tips
プレビュー